Reputation: 11677
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.
Upvotes: 8
Views: 20607
Reputation: 65
Autofocus will select the first record in dropdown search...
Your code would then just need to include autoFocus: true,
like below:
$('#search').autocomplete({
source: url,
delay: 0,
autoFocus: true,
select: function( event, ui ) {
$( "#id" ).val( ui.item.id );
$(this).closest('form').submit();
},
focus: function( event, ui ) { event.preventDefault(); }
});
Upvotes: 0
Reputation: 34107
Hiya demo http://jsfiddle.net/DMDHC/
Hope this helps, :)
So if you type Ra
you will see rambo and other options popping up and then hit tab
key and you will see that added text + " "
will appear with focus on the text box so that you can keep typing.
Another thing I did is event.preventDefault();
which will prevent any default behavior, rest you know what you doing bruv! 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;
}
});
Upvotes: 6
Reputation: 2788
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
Upvotes: 0