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:
You should not use multiple events like this, because it would fire three times as per count of your events one for keydown and for keyup and one for input. Still this is not issue, the issue is the click you are triggering. That is the event of jQuery event object, While you need to fire the click on the DOM.
You should fire the native .click() event of DOM:
$("#modal_confirmation_dp_change").on('keydown', function ( e ) {
var key = e.which || e.keyCode;
if (key == 13) {
$('#changed_dp_ok')[0].click(); // <----use the DOM click this way!!!
}
});
$(document).on('keydown', function(e) {
if (e.which == 13) {
//$('.btn').click(); // <----this wont work
$('.btn')[0].click(); // <---but this works
}
})
Modal Example