Autocomplete: first item focused only when the user type on tab key
Asked Answered
R

1

1

By using jqueryUi autocomplete I would like the first item automatically focused only when the user type on tab key.
How should I perform this task?
Initialising a autocomplete with the autoFocus option true specified does not fit my purpose!

Any ideas?


Here is my code.
Please see the comment for more details.

    element.autocomplete({
        minLength: 3,
        // the following option "autoFocus = true"
        // make the first item focused when the user type the first 3 letters
        // I would like the first item focused only when I type on TAB 
        autoFocus: false,
        source: function (request, response) {
            // some code
        }
    }).data('autocomplete')._renderItem = renderItem;

    // the following piece of code works only when I type the first three letters,
    // If I type four letters and then tab it does not work!
    element.on('keyup', function (event) {
        if (event.keyCode === 9) {
            element.autocomplete( "option", "autoFocus", true );
        }
    });
Recollected answered 20/8, 2012 at 14:7 Comment(2)
Do you have some example code for us to see?Harelda
@JeffreyLo of course. I updated my question with my code and some comments. thanks for your time.Recollected
B
2

Yeah, autoFocus won't do what you want. Instead you can fake the keypresses that a user would normally have to do when they want to select an item.

element.keydown(function(e){
   if( e.keyCode != $.ui.keyCode.TAB ) return; // only pay attention to tabs

   e.keyCode = $.ui.keyCode.DOWN;   // fake a down error press
   $(this).trigger(e);

   e.keyCode = $.ui.keyCode.ENTER;  // fake select the item
   $(this).trigger(e);
});

Demo: http://jsfiddle.net/uymYJ/8/

Besprinkle answered 20/8, 2012 at 14:52 Comment(2)
+1 great. there is just one problem. When clicking on tab I should pass to the other field. Here is jsfiddle.net/uymYJ/4. How can I fix this issue?Recollected
I would recommend finding the next input element and calling .select() on it. I updated the demo to do this.Besprinkle

© 2022 - 2024 — McMap. All rights reserved.