I would like to detect whether the user has pressed any key when a modal is shown. I tried the following code but the events are not fired.
Code snippet:
$("#modal_confirmation_dp_change").on('keydown keyup input', function ( e ) {
alert();
});
If I try to test click event, it is fired.
$("#modal_confirmation_dp_change").on('click', function ( e ) {
alert();
});
I am using twitter bootstrap modal. Am I missing something?
ANSWER:
I found the solution to my problem. It seems like I should not point to the id of the modal so that the keypress event will be detected.
3
Answers
I found the solution to my problem. It seems like I should not point to the id of the modal so that the keypress event will be detected.
You should not use multiple events like this, because it would fire three times as per count of your events one for
keydown
and forkeyup
and one forinput
. Still this is not issue, the issue is theclick
you are triggering. That is the event of jQuery event object, While you need to fire theclick
on the DOM.You should fire the native
.click()
event of DOM:I find it a better solution to give focus to the modal.
In order to do that, you have to add a
tabindex
parameter to your modal container, and then set its focus using JavaScript. Once that’s done it can receive keyboard events: https://stackoverflow.com/a/6633271/2873507