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.
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.
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').
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With