Jquery Chosen - Prevents capture of keypress

好久不见. 提交于 2020-01-05 07:16:02

问题


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?


回答1:


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().




回答2:


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) { . . . });


来源:https://stackoverflow.com/questions/12840814/jquery-chosen-prevents-capture-of-keypress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!