在HTML表单上输入Enter键而不是激活按钮 [英] Making Enter key on an HTML form submit instead of activating button
问题描述
我有一个带有单个提交
输入的HTML表单,还有各种按钮
元素。当用户按下'enter'键时,我期望它实际提交表单,但是(至少在Chrome 15中),我发现它触发了第一个按钮
(因为之前在HTML中发生的比 submit
输入,我想)。
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).
我知道一般来说,你不能强迫浏览器支持特定的 submit
输入,但我真的认为他们会赞成 submit
通过按钮
元素输入。是否有一个小的调整,我可以让HTML做出这个工作,或者我将不得不接受某种Javascript方法?
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?
下面是一个粗略的模型HTML:
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>
推荐答案
您可以使用jQuery:
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;
}
});
});
这篇关于在HTML表单上输入Enter键而不是激活按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!