JQuery AutoComplete: Use the tab to select the first item and stay in the search center.

When I use jQuery UI autocomplete, I need the tab key to fill the search box with the first element in the autocomplete results, then specify a space, then allow the user to continue to enter text.

<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 above example, if someone typed "th", they would see "this" and "that" in the autocomplete options. The β€œOn” tab will add β€œthis” (note the spacebar) to the input, and focus will remain on the input.

Can someone give me a pointer to what I missed? I don't know Javascript very well, so little words are good :)

And perhaps more useful information (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 seems that autoFocus: true will get me there. Now, if I can just figure out how to focus on the input window.

+8
jquery jquery-ui autocomplete
source share
2 answers

Hiya demo http://jsfiddle.net/DMDHC/

Hope this helps :)

So, if you type Ra , you will see rambo and other parameters, and then press the tab key, and you will see that added text + " " appears with focus on the text field so that you can print.

Another thing I did was event.preventDefault(); which will prevent any default behavior, the rest you know what bruv is doing! B -)

jquery code

 $( "#search" ).autocomplete({ source: function( req, resp ) { $.post( "/echo/json/", { json: '["Rambo", "Foobar", "This", "That", "Batman", "Hulk"]', delay: 1 }, function(data) { resp( data ); }, "JSON" ); }, select: function(event, ui) { var TABKEY = 9; this.value = ui.item.value; if (event.keyCode == TABKEY) { event.preventDefault(); this.value = this.value + " "; $('#search').focus(); } return false; } });​ 
+6
source share

I use this (coffeescript):

 $("#autocomplete").keydown (event) -> if event.keyCode != $.ui.keyCode.TAB then return true $(this).trigger($.Event 'keydown', keyCode: $.ui.keyCode.DOWN) false 
0
source share

All Articles