Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing form submission when Enter is pressed [duplicate]

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?

like image 676
Pieter Avatar asked May 10 '10 13:05

Pieter


3 Answers

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; });
like image 66
BalusC Avatar answered Sep 20 '22 04:09

BalusC


Assuming HTML:

<form id="myForm"> ...

You can do this with JavaScript:

document.getElementById("myForm").onsubmit = function () {
    return false;
};
like image 26
Matt Avatar answered Sep 20 '22 04:09

Matt


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;
}
like image 24
Andy E Avatar answered Sep 21 '22 04:09

Andy E