DM_Blunders
DM_Blunders

Reputation: 117

Jquery Chosen - Prevents capture of keypress

I have a div (id = div_search_fields) within which I have several jQuery Chosen dropdowns. Attached to the div I have a keypress capture listener which, if the key pressed is the Enter key, submits the selected stuff by clicking a hidden submit button.

$("#div_search_fields").keypress(function(e) {
    if (e.which == 13) {
        $("#hiddenSubmitButton").click();
    }
});

For some reason this listener is never called if I have just selected an option in one of the chosen dropdowns. Within the "div_search_fields" DIV I also have a simple text input box and if I have just entered text there and then press the Enter key, the listener is triggered as expected.

This must be something to do with focus on the Chosen dropdowns but I cannot fathom why? Any ideas?

Upvotes: 1

Views: 3444

Answers (2)

prakashpoudel
prakashpoudel

Reputation: 577

As Far I can see Jquery chosen is using e.preventDefault() in keypress event so it is not allowing to execute your code. There should be some function which you can override to achieve your goal or you can get ride of e.preventDefault().

Upvotes: 1

Martin
Martin

Reputation: 16300

Two things:

  1. If the input in the dropdowns is generated dynamically AFTER the keypress event is bound, the event won't be bound to those elements.

  2. IDs should be unique to one element. Use a class instead if you want to bind an action to multiple elements.

Use .on() instead:

$(".div_search_fields").on("keypress", function(e) { . . . });

Upvotes: 1

Related Questions