Jquery autocomplete: using tab to select first item and remain focus on search box

When I use the JQuery UI autocomplete, I need to have the tab key populate the search box with the first item in the autocomplete results, include a space afterwards, an then allow the user to continue typing.

<div class="ui-widget">
  <form id="searchbox" method="GET" action="http://duckduckgo.com/">
    <input id="search" type="text" name="q">
    <input id="submit" type="submit" value="Search">
  </form>
</div>
<script>
var tabKey = 9;
$  ('#search').autocomplete({
    source: [ 'this', 'that', 'foobar' ],
    delay: 0,
    selectFirst: true,
    select: function(event, ui) { if (event.keyCode == tabKey) {
      $  ('#search').focus().select();
    } }
});
// without this, the tab key doesn't trigger an event
$  ('.ui-autocomplete').keypress(function(event) {});
</script>

In other words, in the example above, if someone typed “th”, they’d see “this” and “that” in the autocomplete choices. Hitting tab would add “this ” (note the space) to the input and focus would remain in the input.

Can someone give me a pointer as to what I’ve missed? I do not know Javascript very well, so small words are good :)

And perhaps more useful info (jquery 1.7.2) from the HEAD section:

<script src="js/jquery-latest.js"></script>
<script src="js/jquery-ui-1.8.20.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/jquery-ui-1.8.20.custom.css" />

Edit: It appears that autoFocus: true will get me partway there. Now if I can just figure out how to keep focus on the input box.

newest questions tagged jquery – Stack Overflow

About Admin