I have a page in where I have a form and I attach a jquery event handler to submit this form by hitting enter on the keyboard.
//Submit form when enter pressed
$(document).keypress(function (e) {
if (e.which == 13) {
$('form').submit();
}
});
I also have the possibility to show a modal using jquery ui dialog() on the same page. In the modal (which is a hidden div until dialog() is called) there is a button and I would like also to give the user the ability to "click" the button when he hits enter on the keyboard. The problem that I have is if I use the same event handler than previously on my page it will both submit the form and click the button.
How can I handle this so the second event handler is limited to the modal / do not propagate to the rest of the document ? I've tried e.stopPropagation which is not working in that scenario.
//Handler on the modal
$(document).keypress(function(e) {
e.stopPropagation();
if($('#button-doc-validate').is(':visible') && e.which == 13) {
//Click the button
$('#button-doc-validate').click();
}
});