sameucho sameucho - 1 month ago 10
HTML Question

Form not submited on keydown event when event is triggered by 'ESC' key

I need to submit form on hitting the 'ESC' key. I have the folowing code to do so:

<form id="testForm" name="testForm" method="post" action="" >
<input name="givenAnswer" id="realInput" value="" type="text" onclick="doSubmit()" autofocus>
</form>

<script>
document.getElementById('realInput').onkeydown = function(e){
if(e.keyCode == 27){
event.preventDefault();
document.testForm.submit();
}
};
</script>


but this does not work correctly (I try it with FF 47.0.1):
if I type a text to input field, and hit ESC key, form is not submited. The form is submited on ESC key only in the case I click the input filed by mouse right before I hit ESC key (and this is valid only if line 'event.preventDefault();' is excluded from the script). But this is not expected behavoir.

The same is with this script:

<script>
var el = document.getElementById("realInput");
el.onkeydown = function(event) {
if (event.keyCode == 27) {
document.testForm.submit();
}
};
</script>


Would anybody know to tell me what is the problem and suggest solution please?

I foud also these links with similar issue, but the solution proposed there didn't work for me:

location.reload doesn't reload the page when I'm using it in keyDown event handler when ESC is pressed. Only in FF

https://bugs.jqueryui.com/ticket/4922

Thanks

Answer

In your first snippet, Just change event to e in event.preventDefault()