I have a form with a disabled submit button. Even though the user can't press this button, he can still hit Enter to submit the form. How do I prevent that?
If you want to completely disable the form submit (However I am wondering why the whole <form>
element is then there in first place), then you need to let its submit
event handler return false
.
So, basically:
<form onsubmit="return false;">
You can add it using Javascript/DOM manipulation during onload as previous answerers pointed out.
If you only want to disable the Enter key to submit the form, then you need to let its keypress
event handler return false
when the keycode matches 13
(this one is crossbrowser compatible!).
<form onkeypress="return event.keyCode != 13;">
This however also disables the Enter key in any <textarea>
elements in the form. If you have any of them and you would like to keep them functioning, then you'll need to remove the onkeypress
from the <form>
and copy it over all <input>
and <select>
elements. jQuery can be helpful in this:
$('input, select').keypress(function(event) { return event.keyCode != 13; });
Assuming HTML:
<form id="myForm"> ...
You can do this with JavaScript:
document.getElementById("myForm").onsubmit = function () {
return false;
};
Instead of implementing two methods of disabling form submitting, add an event handler to form's onsubmit which will check the disabled
property of the button:
myForm.onsubmit = function () {
if (myForm.mySubmit.disabled)
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