JQuery autocomplete - Select first item
15,531
Solution 1
use autoFocus: true
$( el ).autocomplete({
autoFocus: true
...
});
Solution 2
$( el ).autocomplete({
autoFocus: true
});
Comments
-
RailsSon about 2 years
I am using jquery autocomplete which I am populating from a ruby on rails application and I am creating a custom autcomplete like so:
$.widget( "custom.code_complete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var self = this, currentCategory = ""; $ul = ul; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" ); currentCategory = item.category; } self._renderItem( ul, item ); }); } }); $("#r-code").code_complete({ source: "URL", minLength: 2, select: function(event, ui) { $(".button-row").fadeIn(); get_details(ui.item.url); } });
I am redirecting a user from another page to the page with the autocomplete form with a parameter in the URL which is a code used for the search, here is the JS to do the search:
function ac_search(code) { $("#r-code").val(code); $("#r-code").code_complete('search', code); }
This performs the search perfectly and displays the drop down list of results. I am trying to have the script then select the first result in the list. I have tried doing it via a selector:
$(".ui-menu-item:first a").click();
This finds the correct element in the autocomplete list but when I try and simulate a click it gives this error:
TypeError: ui.item is null
Is it possible to programmatically click the first item in the autocomplete results list?
Cheers
Eef