Reputation: 4212
I have this:
$("#term").autocomplete({
minLength: 2,
source: function( request, response ) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + escape(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return { label: item.suggestion.data, value: item.suggestion.data };
}));
}
});
}
});
So the autocomplete has a build in for keyup event. But how do I give the same 'function( request, response )' when clicking something (= ul li in this case)? How do I attach onclick event to do the autocomplete?
here is live version: JsBin
Upvotes: 1
Views: 2392
Reputation: 69905
Use select
event and then trigger autocomplete search by passing the value which you can get from the event arguments.
select: function(e, ui){
$("#term").autocomplete('search', ui.item.value);
}
Upvotes: 2
Reputation: 30666
Your question is not very clear. As far as I understood, the plugin provides a "search" method to programmatically initiate a search, like you would if you were typing in the input field directly.
The use is the following:
$('#term').autocomplete('search', 'Napoleon');
If you want to start a new suggestion each time an element is selected in the menu, you can use the select
event. It is trigerred when an element is selected from the suggestion list, either by cliking an item, or with keyboard:
$("#term").autocomplete({
...,
select: function(e, ui) {
$('#term').val(ui.item.value).autocomplete('search', ui.item.value);
}
});
The property ui.item
is the data item that was selected.
I've set-up a demo where cliking a button will search for the term associate to a "data-" attribute:
Further reading:
Upvotes: 1
Reputation: 6047
I am a bit lost with the ) and } in my snippet, but you should use the select
option
$("#term").autocomplete({
source: function(request, response){
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + escape(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion,
function(item) {
return { label: item.suggestion.data, value: item.suggestion.data };
}));
} /* end succes function */
}); /* end ajax function */
}, /* end source function */
minLength: 2,
select: function(event, ui) {
$("#term").val(ui.item.value); /* to set the clicked value in the input */
$("#btn").click(); /* to submit the form, replace with your button*/
}
});
EDIT: I added some comments for myself to check if there where missing brackets (lol)
Upvotes: 1