My sources are JSON objects that fetched from url and it looks like below.
[
{"ID":1,"GROUP_ID":"1","CONTACTNAME":"Mizuki","PHONENUMBER":"+6289695049930"},
{"ID":15,"GROUP_ID":"3","CONTACTNAME":"Sinbad","PHONENUMBER":"+6287654321"},
{"ID":23,"GROUP_ID":"","CONTACTNAME":"Titus","PHONENUMBER":"+6255555555"}
];
When user typing, result of suggestion is CONTACTNAME and value that inserted into searchbox is PHONENUMBER. Fetch data from source/url have no issue but in searchbox there's no value passed.
Screenshot below
Here's my script
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
});
Form view
<input type="text" v-model="message.DESTINATIONNUMBER" id="tags" class="form-control" name="destinationNumber" >
I try to remove vue snippet (v-model) still same.
Any suggestion? Whats wrong?
UPDATED!!
My mistake. Forgot add this code at the end.
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
So, full javascript is like in jquery-ui docs
$(function() {
$( "#contact" ).autocomplete({
source: "api/contact/auto",
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
Thanks for people who try to help me. Appreciate it.
For the autocomplete to work, you need to have "label" attribute in the returned JSON array. You can either change that on the server side, or transform it on the client as follows:
$( "#contact" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "api/contact/auto",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.CONTACTNAME,
value: el.PHONENUMBER,
id: el.ID
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
minLength: 1,
focus: function( event, ui ) {
$("#contact").val(ui.item.CONTACTNAME);
return false;
},
select: function( event, ui ) {
$("#contact").val(ui.item.PHONENUMBER);
return false;
}
});
There were a couple of errors in your JavaScript:
"source" is misspelled ("sorGce")
in availableTags indexes except 0, the colon is inside the quotes instead of outside
Working fiddle:
sorGce: availableTags, -> source: availableTags,
"ID:" "23", -> "ID": "23",
https://jsfiddle.net/ep1s9w3s/1/
Not sure if this is the root cause of your problem or not, but it might help you fix your fiddle.
Related
I'm just trying something out, as an experiment, with the jQuery autocomplete widget.
I used this as an example: Autocomplete | APi Data
But when i try it, it's not filtering the results. it only shows all results when i type something and then 'backspace-it-all'
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
console.log(data)
response( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
console.log(item.value)
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
</script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>
The only issue with your code is, you are fetching data in function but not filtering the data.
You just need to filter your data using the following line. Here final_data is nothing but your resulted output.
response($.ui.autocomplete.filter(final_data, request.term));
Try below code.
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
var final_data =( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
response($.ui.autocomplete.filter(final_data, request.term));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>
How to map a complex nested json to jquery autocomplete format? I tried to map my custom json to the required jquery autocomplete format label, value, ... but my list is 'undefined'. This is my setup:
JSON:
{"data":[{"DT_RowId":"row_A6J851","accounts":{"code":"A6J851","name":"Peter Jackson"}},{"DT_RowId":"row_1D01Q14","accounts":{"code":"1D01Q14","name":"Earl Bundy"}}]}
Javascript:
$('#input-search').autocomplete({
source: function ( request, response ) {
$.ajax({
type: 'GET',
url: '/source.php',
dataType: "json",
success: function( data ) {
response( $.map( data.data.accounts, function( value, key ) {
return {
label: value.name,
value: value.name,
id: value.code
}
}));
}
});
},
create: function() {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $( "<li></li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
}
});
It looks like from your data example that you are not iterating over the nested accounts array, but rather the data array. Try something like this:
$('#input-search').autocomplete({
source: function ( request, response ) {
$.ajax({
type: 'GET',
url: '/source.php',
dataType: "json",
success: function( data ) {
var results = [];
$.each(data.data, function(d){
var mapped = $.map(d.accounts, function( value, key ) {
return {
label: value.name,
value: value.name,
id: value.code
};
})
results = results.concat(mapped);
});
response(results);
}
});
},
create: function() {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $( "<li>" )
.append( "<span>" + item.label + "</span>" )
.appendTo( ul );
};
}
});
I am using jquery modal, within each modal I have a form. I am then loading certain jquery functions onto the form elements, for example jquery autocomplete.
When I open the modal for the first time it is working fine with all the jquery functions within the script, but as soon as I close the first modal and open again none of the functions work.
Its as though they are binded on the page load to the form, then when the button is clicked for the modal its works and then closing the modal unbinds it.
Does anybody have any ideas as to why they would stop working after the first modal open/close?
$(document).ready(dialogForms);
function dialogForms() {
$('a.menubutton').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
if($(this).find('form').valid()){
// do stuff if form validates
submitFormWithAjax($(this).find('form'));
$('#homepage').trigger('click');
$(this).dialog('close');
}
else {
}
},
'Cancel': function() {$(this).dialog('close');}
},
width: 650,
height: 400,
show: "fade",
hide: "fade"
});
$('#edit_vle').bind('change', function (e) {
if( $('#edit_vle').val() == 'FE') {
$('#fe_automcomplete1').show();
$('#he_automcomplete1').hide();
$("#edit_he_title").val("");
$("#edit_he_code").val("");
}
else{
$('#fe_automcomplete1').hide();
$('#he_automcomplete1').show();
$("#edit_fe_title").val("");
$("#edit_fe_code").val("");
}
});
$('#delete_vle').bind('change', function (e) {
if( $('#delete_vle').val() == 'FE') {
$('#fe_automcomplete2').show();
$('#he_automcomplete2').hide();
$("#delete_he_title").val("");
$("#delete_he_code").val("");
}
else{
$('#fe_automcomplete2').hide();
$('#he_automcomplete2').show();
$("#delete_fe_title").val("");
$("#delete_fe_code").val("");
}
});
var epronames = [<?php
$eprotmp = Array();
while($eprorow = mssql_fetch_array($epro_course)) $eprotmp[] =
'{
title: "'.$eprorow['Name'].'",
label: "'.$eprorow['Code'].' - '.$eprorow['Name'].'",
code: "'.$eprorow['Code'].'",
user: "'.$eprorow['fname'].' '.$eprorow['sname'].'",
}';
echo join(',', $eprotmp);
?>];
var fenames = [<?php
$fetmp = Array();
while($ferow = mysql_fetch_array($feinactive)) $fetmp[] =
'{
title: "'.$ferow['course'].'",
label: "'.$ferow['shortname'].' - '.$ferow['course'].'",
code: "'.$ferow['shortname'].'",
}';
echo join(',', $fetmp);
?>];
var henames = [<?php
$hetmp = Array();
while($herow = mysql_fetch_array($heinactive)) $hetmp[] =
'{
title: "'.$herow['course'].'",
label: "'.$herow['shortname'].' - '.$herow['course'].'",
code: "'.$herow['shortname'].'",
}';
echo join(',', $hetmp);
?>];
$("#title").autocomplete({
minLength: 3,
source: epronames,
focus: function( event, ui ) {
$("#title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#title").val( ui.item.title );
$("#code").val( ui.item.code );
$("#ctl").val( ui.item.user );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("#edit_he_title").autocomplete({
minLength: 3,
source: henames,
focus: function( event, ui ) {
$("#edit_he_title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#edit_he_title").val( ui.item.title );
$("#edit_he_code").val( ui.item.code );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#edit_he_title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$("#edit_fe_title").autocomplete({
minLength: 3,
source: fenames,
focus: function( event, ui ) {
$("#edit_fe_title").val( ui.item.label );
return false;
},
select: function( event, ui ) {
$("#edit_fe_title").val( ui.item.title );
$("#edit_fe_code").val( ui.item.code );
return false;
},
change: function(event, ui) {
if (!ui.item) {
$("#edit_fe_title").val("");
}
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
if($("#clearform").length > 0){
$("#clearform").click(function() {
$("#title").val('');
$("#code").val('');
$("#ctl").val('');
});
}
if($("#delete_fe_clearform").length > 0){
$("#delete_fe_clearform").click(function() {
$("#delete_fe_title").val('');
$("#delete_fe_code").val('');
});
}
if($("#edit_fe_clearform").length > 0){
$("#edit_fe_clearform").click(function() {
$("#edit_fe_title").val('');
$("#edit_fe_code").val('');
});
}
if($("#delete_he_clearform").length > 0){
$("#delete_he_clearform").click(function() {
$("#delete_he_title").val('');
$("#delete_he_code").val('');
});
}
if($("#edit_he_clearform").length > 0){
$("#edit_he_clearform").click(function() {
$("#edit_he_title").val('');
$("#edit_he_code").val('');
});
}
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
}
});
return false;
}
Here are the buttons for each modal.
New Course
Edit Course
Delete Course
I placed the jquery functions into the open method
open: function(){
To close the dialog instead of using:
$(this).dialog('close');
I used
dialog.remove();
My functions now work every time i open the dialog
I have autocomplete working on my site with the following:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
}
});
});
What I want to do now is that when a user types in something that is not shown on the dropdown, I'd like for the following to take place:
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
I tried using the following but it didn't work:
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
if(typeof(ui.item)){
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
} else {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
}
});
});
the select evevnt is only triggered when you select an item in dropdown
you could do it on search event
$(function () {
$("#client").autocomplete({
source: "/appointments/clients.json",
minLength: 1,
select: function (event, ui) {
$('input[name="clientid"]').val(ui.item.id);
$('#app-submit').html('Add Appointment for ' + ui.item.value);
},
search: function() {
$('input[name="clientid"]').val('');
$('#app-submit').html('Add Appointment');
}
});
});
I don't know what the whole idea is without seeing markup. But my guess is:
$("#client").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/appointments/clients.json",
dataType: "jsonp",
success: function( data ) {
var suggestions = $.map( data, function( item ) {
return {
label: item.value,
value: item.id
}
});
// idea: whatever I have, extend to extra item.
suggestions.push({
label: 'Add appointment',
value: 0
});
response( suggestions );
}
});
},
select: function(evt, ui){
if( ui.item.label == 'Add appointment'){
/* do something special with it */
}else{
/* blah blah */
}
}
});
How can I use the selected item from a jQuery-ui autocomplete in a further jQuery-ui autocomplete function?
e.g. for this HTML:
<div class="ui-widget">
<label for="project">Project: </label>
<input id="project" />
<label for="phase">Phase: </label>
<input id="phase" />
<label for="filename">Project: </label>
<input id="filename" />
</div>
I am using the following autocomplete function with a JSON endpoint to supply the data.
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
}
});
});
Then in this second autocomplete I want to take the selected value from the first autocomplete function and use it to build the URL string for use in the source attribute of a second autocomplete (shown here as valueFromFirstAutocomplete).
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+valueFromFirstAutocomplete,
minLength: 2,
select: function( event, ui ) {
}
});
});
Customize the source option with a callback, adding the additonal parameter to the URL:
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2
});
$( "#phase" ).autocomplete({
source: function(request, response) {
$.get(baseUrl + "/json/listphases/" + $("#project").val(), request, response);
},
minLength: 2
});
You could just put one inside the other....
Is there some reason this won't work?
$(function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: function( event, ui ) {
$(function() {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: function( event, ui ) {
}
});
});
}
});
});
To use these independently you could do something like this:
var funclist = {
populate1 : function() {
$( "#project" ).autocomplete({
source: baseUrl+"json/listtitles",
minLength: 2,
select: populate2;
},
populate2 : function(event,ui) {
$( "#phase" ).autocomplete({
source: baseUrl+"json/listphases/"+ui.item.value,
minLength: 2,
select: populate3;
}
populate3 : ; // etc
}
$(funclist.populate1);