Implementing jQuery Autocomplete in many inputs in a page
I h开发者_C百科ave an autocomplete which takes results from google suggestions. On a page I have multiple input fields which I'd like to include that function so that all inputs will be taking results from google suggestion and using the jquery autocomplete widget.
Here is a Fiddle: http://jsfiddle.net/8q25P/
Note on the first input it parse's google queries. On the second which has different ID its where I want to implement the feature aswell.
Thanks alot
Here are the changes..
http://jsfiddle.net/gaby/ag9gv/
First you need to apply the autocomplete to both elements and also bind the retrieve
to both.
$('#q, #w').keyup(retrieve);
and
$('#q, #w').autocomplete({
source: []
});
You also need to change your ajax call and the retrieve method a bit, to make the related element auto-discoverable.. (create a variable and pass it to the success method)
function retrieve() {
var _this = this;
$.ajax({
type: "GET",
url: 'http://suggestqueries.google.com/complete/search?qu=' + encodeURIComponent($(this).val()),
dataType: "jsonp",
success: function(data){parse(data,_this);}
});
}
var parse = function(data,element) {
var results = [];
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i][0]);
}
$(element).autocomplete({
source: results
});
}
Add a class to each input and bind the autocomplete to an input with a class of that class
$(input.class).autocomplete()
精彩评论