Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Enter key on an HTML form submit instead of activating button

Tags:

html

jquery

forms

I have an HTML form with a single submit input, but also various button elements. When the user presses the 'enter' key, I'd expect it to actually submit the form, but instead (within Chrome 15 at least) I'm finding that it's triggering the first button (since that occurs earlier in the HTML than the submit input, I guess).

I know that in general you can't force browsers to favour a particular submit input, but I really thought they would favour submit inputs over button elements. Is there a small tweak I can make to the HTML to make this work, or am I going to have to embrace some kind of Javascript approach?

Here's a rough mockup of the HTML:

<form action="form.php" method="POST">     <input type="text" name="field1"/>     <button onclick="return myFunc1()">Button 1</button>     <input type="submit" name="go" value="Submit"/> </form> 
like image 331
andygeers Avatar asked Nov 28 '11 10:11

andygeers


People also ask

How do I make a form so it can be submitted by hitting Enter in HTML?

HTML form submit on Enter Key | Example code You don't need to use JavaScript to do submit button or input on entering key pressed. Just need to mark it up with type="submit" , and the other buttons mark them with type="button" .

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 do you make input submit on enter?

Enter = SubmitIf you have focus in the textbox and hit enter, the form will be submitted automatically. This behavior is consistent across all browsers and is known as implicit submission.


1 Answers

You don't need JavaScript to choose your default submit button or input. You just need to mark it up with type="submit", and the other buttons mark them with type="button". In your example:

<button type="button" onclick="return myFunc1()">Button 1</button> <input type="submit" name="go" value="Submit"/> 
like image 150
Jesús Carrera Avatar answered Oct 05 '22 12:10

Jesús Carrera