I’ve come up against a weird problem when trying to cancel a form submit when the enter key is pressed in a text box.
Using the code below the form always submits when enter is pressed after I close the alert. If I comment out the alert the form no longer submits on enter, the desired result.
<input id="myTextBox" type="text" onkeydown="return myFunction(event);">
function SearchOnEnter(event) {
var key = event.charCode || event.keyCode || e.which || 0;
if (key == 13) {
alert('Test text.');
return false;
}
else
return true;
}
Is there a way to get the form not to submit after showing the alert? Also any idea why the alert box is causing this problem?
Thanks
UPDATE, this doesn’t seem to be an issue on IE, affects Firefox and chrome.
You are returning
falsefor thekeydownevent, not for thesubmitevent. This way, form submission will go ahead unchanged.It may be possible to stop the event in the
keydownhandler which might be the most elegant solution – I don’t know, maybe somebody comes up with a suggestion for that.Meanwhile, as another option, you could set a “do not submit form” flag in the
keydownevent that you then check for in the form’ssubmitevent.Untested but should work somewhere along these lines:
I’m not 100% sure OTOH whether it’s possible to assign properties to DOM elements like that (
this.do_not_submit) but I’m pretty sure it is.