5

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

RailsSon
  • 19,897
  • 31
  • 82
  • 105

2 Answers2

19
$( el ).autocomplete({
  autoFocus: true
});
sdespont
  • 13,915
  • 9
  • 56
  • 97
aprencai
  • 396
  • 2
  • 10
15

use autoFocus: true

 $( el ).autocomplete({
      autoFocus: true
      ...
 });
Irishka
  • 1,136
  • 6
  • 12
  • You don't really need this extension when you can just set the autoFocus option as true. – Ziad Feb 05 '13 at 07:14