I know this question has been asked before but I could not find a satisfactory answer for my situation. So I am asking again.
I have a simple form with 2 text boxes and a submit button. After the user enters text in either text box they should not be able to submit through the Enter key, only the submit button should allow them to submit. I thought trapping the enter keypress and returning false from the onChange event handler would do the trick but apparently not, this still causes a form submission...
function doNotSubmit(element) {
alert("I told you not to, why did you do it?");
return false;
}
</script>
<form id="myForm" action="MyBackEnd.aspx" method="post">
<table>
<tbody>
<tr>
<td>
Joe: <input id="JoeText" type="text" onChange="doNotSubmit(this)">
</td>
<td>
Schmoe: <input id="SchmoeText" type="text" onChange="doNotSubmit(this)" >
</td>
</tr>
</tbody>
</table>
<input type=submit>
I tested on both Chrome and FF (latest versions).
Can you please show me how to prevent the form submission?
Thanks.
You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.
to piggy back on @Dasein's anwser you want to prevent the default behavior instead of stopping propagation ( i.e. returning false):
document.getElementById("myForm").onkeypress = function(e) {
var key = e.charCode || e.keyCode || 0;
if (key == 13) {
alert("I told you not to, why did you do it?");
e.preventDefault();
}
}
<form id="myForm" action="MyBackEnd.aspx" method="post">
<table>
<tbody>
<tr>
<td>
Joe: <input id="JoeText" type="text">
</td>
<td>
Schmoe: <input id="SchmoeText" type="text" >
</td>
</tr>
</tbody>
</table>
<input type=submit>
I think this should do:
document.getElementById("myInput").onkeypress = function(e) {
var key = e.charCode || e.keyCode || 0;
if (key == 13) {
alert("I told you not to, why did you do it?");
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With