Making Enter key on an HTML form submit instead of activating button
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>
Solution 1:
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"/>
Solution 2:
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
Solution 3:
Try this, if enter key was pressed you can capture it like this for example, I developed an answer the other day html button specify selected, see if this helps.
Specify the forms name as for example yourFormName
then you should be able to submit the form without having focus on the form.
document.onkeypress = keyPress;
function keyPress(e){
var x = e || window.event;
var key = (x.keyCode || x.which);
if(key == 13 || key == 3){
// myFunc1();
document.yourFormName.submit();
}
}
Solution 4:
I just hit a problem with this. Mine was a fall off from changing the input
to a button
and I'd had a badly written />
tag terminator:
So I had:
<button name="submit_login" type="submit" class="login" />Login</button>
And have just amended it to:
<button name="submit_login" type="submit" class="login">Login</button>
Now works like a charm, always the annoying small things... HTH