Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit on keyCode == "enter" (13)

I need to submit the content of a form when I press the Enter key, but only if the form has no error message. I built up the following function:

$(targetFormID).submit(function (e) {
    var mess = error_m(targetDiv);
    if (e.keyCode == 13 && mess.length > 0) {
        e.preventDefault();
        e.stopPropagation();
    }
    if (mess.length == 0 && e.keyCode == 13) $(targetFormID).submit();
}); 

In this function the mess variable is getting the error message returned by function error_m, the rest is simple code condtion but it doesn't work.

Need some help with this!!

like image 206
sorin Avatar asked Jan 10 '12 12:01

sorin


People also ask

What is e KeyCode === 13?

Keycode 13 is the Enter key.

How do I submit a form using Enter?

To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.

How do I stop form submit on enter key press?

addEventListener("submit",function(e){e. preventDefault(); return false;}); This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.


1 Answers

Submitting the form when the Enter key is pressed is default browser behaviour. Don't mess with it. Just validate the form in the submit event.

$(targetFormID).submit(function (e) {
    var mess = error_m(targetDiv);
    if (mess.length > 0) {
        e.preventDefault();
    }
});

One other possible problem: what is targetFormID? If it's actually a string containing an element ID, you'll need

$("#" + targetFormID).submit(/* Same function as above */);

If it's a reference to the form element then $(targetFormID) is fine but your variable is misleadingly named.

like image 150
Tim Down Avatar answered Sep 21 '22 17:09

Tim Down