Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a form when the return key is pressed?

Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form? The submit button is not there. I am using a custom div instead of that.

like image 520
Niyaz Avatar asked Aug 27 '08 11:08

Niyaz


People also ask

How do you submit a form when Enter key is pressed?

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 can I submit a form without entering the key?

You can bind the keydown event on just the form, instead of binding the individual inputs: the keydown event will propagate up to the form. If your form had multiple input elements then slightly better would be to bind the handler to the form and filter for events from input elements like this: $('#form').

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.


2 Answers

To submit the form when the enter key is pressed create a javascript function along these lines.

function checkSubmit(e) {    if(e && e.keyCode == 13) {       document.forms[0].submit();    } } 

Then add the event to whatever scope you need eg on the div tag:

<div onKeyPress="return checkSubmit(event)"/>

This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).

like image 59
John Hunter Avatar answered Sep 26 '22 01:09

John Hunter


IMO, this is the cleanest answer:

<form action="" method="get">    Name: <input type="text" name="name"/><br/>    Pwd: <input type="password" name="password"/><br/>    <div class="yourCustomDiv"/>    <input type="submit" style="display:none"/>  </form>

Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.


It has been noted that display:none will cause IE to ignore the input. I created a new JSFiddle example that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from StriplingWarrior.

like image 44
Chris Marasti-Georg Avatar answered Sep 26 '22 01:09

Chris Marasti-Georg