Autocomplete using jQuery callback (label/value pair)
I am trying to implement autocomplete jQuery, but am not understanding the autocomplete function that jQuery UI provides.
It uses a callback function and gets the response as a label/value pair. I have some sample code where I am trying to pass an arbitrary label/value pair back and display that option but it isn't working. If someone can help me out with that or show me a simple program it will be great.
http://jsfiddle.net/kB25J/
HTML:
<html>
<body>
Please enter your country name
<input id ="book" type="text" value="">
</body>
</html>
JavaScript:
$("#book").autocomplete({
source: function(request, response) {
alert(request.term);
response(function() {
return {
label: "hi",
value: "bye"
}
});
alert(reponse);
}
});
Thank You
发送响应时,传递数组而不是函数。
$(function() {
$("#book").autocomplete({
source: function(request, response) {
var data = [{
label: "hi",
value: "bye"
}];
response(data);
},
select: function( event, ui ) {
$( "#book" ).val( ui.item.label); //ui.item is your object from the array
return false;
}
});
});
You should be returning an array in your source even if its just 1 match in this case 'hi'/'bye'
As seen in this example on jqueryui.com
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
Its returning an array of key/value pairs for label/value using a map on the remote response.
If your source is just a list of countries you can just use an array of strings as your source.
var countries = ["USA", "Canada", "Mexico", ...]
$('input').autocomplete({
source : countries
});
If you are working with a remote source:
$('input').autocomplete({
source : function (request, response) {
$.ajax({
url: "url_to_get_countries",
dataType: "json",
success: function( data ) {
response( $.map( data.countries, function( item ) {
return {
label: item.country_name,
value: item.country_id
}
}));
}
});
}
});
@LakshmikanthanVijayaraghavan
As you can see at Autocomplete guide, there are three ways to implement autocomplete with jquery plugin.
The first two options are for a fixed list of values. If you want to populate the autocomplete list dinamically, you have to implement the last one.
To do that, you have to specify an url to get the objects array. If you want to keep the label and the key hidden, you need to create an input type hidden and set his value too.
For example
$( "#book" ).autocomplete({
source: "getValues.htm",
select: function(event, ui) {
$( "#book" ).val(ui.item.label);
$( "#book_hidden" ).val(ui.item.value);
return false;
}
});
getValues.html must return the array of label/values pair.
Hope this helps
链接地址: http://www.djcxy.com/p/65278.html