在HTML表单上输入Enter键而不是激活按钮 [英] Making Enter key on an HTML form submit instead of activating button

查看:99
本文介绍了在HTML表单上输入Enter键而不是激活按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有单个提交输入的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆