detect key press on modal dialog not working
Solution 1
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.
$(document).on('keydown keyup input click', function (e) {
if($('#modal_confirmation_dp_change').is(':visible')) {
var key = e.which;
if (key == 13) { //This is an ENTER
$('#changed_dp_ok').click();
}
}
});
Solution 2
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
}
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Related videos on Youtube
![Marss](https://i.stack.imgur.com/dSUmf.jpg?s=256&g=1)
Marss
Updated on September 16, 2022Comments
-
Marss almost 2 years
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.
-
Jai over 8 yearscheck the snippet added.