用输入键防止表单提交 [英] Prevent form submission with enter key

查看:85
本文介绍了用输入键防止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I just wrote this nifty little function which works on the form itself...

我只写了这个很漂亮的小函数, .keypress(function(e){
if(e.which == 13){
var tagName = e.target.tagName.toLowerCase();
if(tagName!== textarea){
return false;
}
}
}

$("#form").keypress(function(e){ if (e.which == 13) { var tagName = e.target.tagName.toLowerCase(); if (tagName !== "textarea") { return false; } } }

在我的逻辑中,我希望接受在输入textarea期间输入的内容,并且还可以将输入字段的输入键行为替换为行为,以便将其标记到下一个输入字段(就像Tab键是)有人知道使用事件传播模型正确地在合适的元素上触发回车键的方法,但是防止表单提交就是按下。

In my logic I want to accept enters during input of a textarea. Also would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on it's press.

推荐答案

下面是我的函数的一个修改版本,它执行以下操作:

Here is a modified version of my function. It does the following:


  1. 防止输入密钥来自对任何其他
    形式的任何元素使用
    ,而不是textarea n,提交。

  2. 现在,Enter键就像是一个选项卡。
  3. 在元素上调用preventDefault(),stopPropagation()但在表单上调用似乎会阻止事件进入元素。

所以我的解决方法是检查元素类型,如果类型不是textarea(允许进入),或者按钮/提交(enter = click),那么我们只是选中下一件事。

So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.

调用.next()元素是没有用的,因为其他元素可能不是简单的兄弟姐妹,但是因为DOM在选择时几乎保证了订单,所以一切都很好。

Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
                if (this === e.target) {
                    focusNext = true;
                }
                else if (focusNext){
                    $(this).focus();
                    return false;
                }
            });

            return false;
        }
    }
}

这篇关于用输入键防止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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