Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a button to submit on enter key

I have two buttons one with id=enterToSubmit and other with id=clickToSubmit. When a user hit the enterkey, I want "enterToSubmit" button to submit form not the "clickToSubmit" button.

On the same page, I have a textbox id=title, and on Page Load I hide "enterToSubmit " button, until user enters something in the textbox, then users can hit Enter key to submit form.

How do preven "clickToSubmit" button to submit when users press Enter key?

like image 270
ɹǝʞɐǝɹq-ʞɔɐʇs Avatar asked Nov 02 '10 06:11

ɹǝʞɐǝɹq-ʞɔɐʇs


2 Answers

How do preven "clickToSubmit" button to submit when users press Enter key?

Try this:

$("#clickToSubmit").on("keydown", function(e){
   if(e.keyCode === 13){
       e.preventDefault();
   }
});
like image 191
Sarfraz Avatar answered Nov 11 '22 10:11

Sarfraz


    $('#formId').on('keyup keypress', function(e) {
          var keyCode = e.keyCode || e.which;
          if (keyCode === 13) { 
            e.preventDefault();
            return false;
          }
        });



Usually form is submitted on Enter when you have focus on input 
elements.
We can disable Enter key (code 13) on input elements within a form.

Also, As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well.

like image 40
AVISHEKKT47 Avatar answered Nov 11 '22 09:11

AVISHEKKT47