Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery-autocomplete: makes the tab key select the first item if no item is selected

The goal of this question is: by using jquery-autocomplete, makes the tab key able to select the first item if no item is selected.

The code I have implemented (1) works but I have some doubts and I would like to clarify them or, if it is possible, improve/change the code (1) in order to achieve my goal.

My doubts are:

I am triggering ENTER too early: the event dispatching is asynchronous (the different listeners are called synchronously, but it is asynchronous of the trigger), so I may trigger it before the listener handled DONE).
Thus, I am still using the same object for both events here, so I may have nasty side effects (if I prevent the default during the first dispatching, it will be prevented for the second one too as it is the same object for instance).

Any suggestion/comment?

P.S.:

  1. Here is the jsfiddle link: http://jsfiddle.net/uymYJ/31/.
  2. This question is related to this one How to avoid to modify the event object in this situation.

(1)

$("#box").keydown(function(event){
    var newEvent = $.Event('keydown', {
        keyCode: event.keyCode
    });

    if (newEvent.keyCode !== $.ui.keyCode.TAB) {
        return;
    }

    newEvent.keyCode = $.ui.keyCode.DOWN;
    $(this).trigger(newEvent);

    newEvent.keyCode = $.ui.keyCode.ENTER;
    $(this).trigger(newEvent);
});
like image 878
js999 Avatar asked Aug 22 '12 12:08

js999


1 Answers

I think you need something like this:

$("#box").keydown(function(event){
    var newEvent = $.Event('keydown', {
        keyCode: event.keyCode
    });

    if (newEvent.keyCode !== $.ui.keyCode.TAB) {
        return;
    }

    if (newEvent.keyCode == $.ui.keyCode.TAB) {
        // custom logic for tab
        newEvent.keyCode = $.ui.keyCode.DOWN;
        $(this).trigger(newEvent);
        return false;
    }

    // ...
});
like image 103
Serhiy Avatar answered Sep 24 '22 20:09

Serhiy