Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a form on 'Enter' with jQuery?

I have a bog-standard login form - an email text field, a password field and a submit button on an AIR project that's using HTML/jQuery. When I hit Enter on the form, the entire form's contents vanish, but the form isn't submitted. Does anyone know if this is a Webkit issue (Adobe AIR uses Webkit for HTML), or if I've bunged things up?

I tried:

$('.input').keypress(function (e) {   if (e.which == 13) {     $('form#login').submit();   } }); 

But that neither stopped the clearing behavior, or submitted the form. There's no action associated with the form - could that be the issue? Can I put a javascript function in the action?

like image 396
b. e. hollenbeck Avatar asked Mar 30 '09 21:03

b. e. hollenbeck


People also ask

How Prevent form submit on Enter key press jQuery?

getElementById("testForm"); form. 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.

How can we submit a form using jQuery?

jQuery submit() Method The submit event occurs when a form is submitted. This event can only be used on <form> elements. The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.

How do you set enter key as submit form in JavaScript?

Using JavaScript In vanilla JavaScript, you can bind an event handler to the keyup event using the addEventListener() method and use the KeyboardEvent. code property to determine whether an Enter key is pressed. Finally, trigger the form's submit event on Enter keypress.

How do you trigger button click on Enter key press using JavaScript?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.


2 Answers

$('.input').keypress(function (e) {   if (e.which == 13) {     $('form#login').submit();     return false;    //<---- Add this line   } }); 

Check out this stackoverflow answer: event.preventDefault() vs. return false

Essentially, "return false" is the same as calling e.preventDefault and e.stopPropagation().

like image 195
NoBrainer Avatar answered Oct 15 '22 11:10

NoBrainer


In addition to return false as Jason Cohen mentioned. You may have to also preventDefault

e.preventDefault(); 
like image 41
bendewey Avatar answered Oct 15 '22 10:10

bendewey