Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery autocomplete - Select first item [duplicate]

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

like image 488
RailsSon Avatar asked Nov 07 '11 11:11

RailsSon


1 Answers

$( el ).autocomplete({
  autoFocus: true
});
like image 172
aprencai Avatar answered Sep 28 '22 09:09

aprencai