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

1

7

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);
});
Deaf answered 22/8, 2012 at 12:7 Comment(5)
Would you mind if I ask you what is $.Event? I found nothing in jQuery API, but console.log($.Event) outputs function. Can you provide a link to the docs?Gragg
@caligula, thanks for your comment. Here is the link api.jquery.com/category/events/event-object. In my code: jQuery.Event is equal to $.EventDeaf
Just to clarify - you only want the tab key select the first item, meaning you want to disable the up+down arrows?Qktp
@Qktp I want to keep the same behaviour and add the following: tab key select the first item if no item is selected.Deaf
possible duplicate of jQuery autocomplete manual input (altough no answer)Derian
U
3

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;
    }

    // ...
});
Unaesthetic answered 23/8, 2012 at 11:14 Comment(2)
+1 Thanks for your answwer. Can you explain the reason of your choise? thanks.Deaf
I think you need to make some custom TAB press behavior. Becaus default one is not proper for you task.Unaesthetic

© 2022 - 2024 — McMap. All rights reserved.