在 HTML 表单提交中使用 Enter 键而不是激活按钮

我有一个具有单个 submit输入的 HTML 表单,但也有各种 button元素。当用户按下“ Enter”键时,我希望它实际上提交表单,但是相反(至少在 Chrome 15中)我发现它触发了第一个 button(因为这在 HTML 中比 submit输入更早发生,我猜)。

我知道一般情况下你不能强迫浏览器偏爱某个特定的 submit输入,但是我真的认为他们会偏爱 submit输入而不是 button元素。我是否可以对 HTML 进行一些小的调整以使其工作,或者我是否必须采用某种 Javascript 方法?

下面是 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>
166360 次浏览

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;
}
});
});

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();
}
}

Given there is only one (or with this solution potentially not even one) submit button, here is jQuery based solution that will work for multiple forms on the same page...

<script type="text/javascript">
$(document).ready(function () {


var makeAllFormSubmitOnEnter = function () {
$('form input, form select').live('keypress', function (e) {
if (e.which && e.which == 13) {
$(this).parents('form').submit();
return false;
} else {
return true;
}
});
};


makeAllFormSubmitOnEnter();
});
</script>

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"/>

I just gave this a whirl in both Chrome and Firefox and IE10.

As mentioned above - make sure that you have marked up with type = "button", "reset", "submit" etc to ensure that it correctly cascades and chooses the correct button.

Perhaps also setting all of them to have the same form (ie all as that worked for me)

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

$("form#submit input").on('keypress',function(event) {
event.preventDefault();
if (event.which === 13) {
$('button.submit').trigger('click');
}
});