繁体   English   中英

在jQuery中检测Textarea对象

[英]Detecting Textarea Object in jQuery

当客户填写我们的表单时,我有一些jQuery可以抑制回车:

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :not(:button, :submit)').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

但是,它也设法抑制了我们的注释框中的回车。

像添加现有代码必须检查:not(:button,:submit)一样,添加textarea检查器似乎很简单:

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :not(:button, :submit, :textarea)').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

哎呦! :not(:button,:submit,:textarea)不起作用,因为似乎没有为jQuery的这一部分定义textarea

其他人如何检测到这些TextArea控件?

更新:

一位在此处发布答案的人竟然找到了解决方案。

我们所有表单生成的eForm类以某种方式捕获了这一点。

我的经理和我花了几个小时来解决这个问题,但是最后我要做的就是只处理Input控件中的事件。

这是我们的最终结果:

$('form.eForm:not(.suppress-submit-on-enter-key-disabled) :input:not(:button, :submit, textarea)').keypress(function (e) {
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

特别感谢Khawer Zeshan提供的小提琴。 它向我证明了我的代码有更深层的错误。

为什么不对单个textarea使用id ,而对多个选择器使用class名称呢?

仅用于一个textarea

$('#textareaid').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

对于多个字段,请使用class name ,并将相同的类应用于这些字段:

$('.textareaClass').keypress(function(e){
  if(e.which == 13){
    // Cancel submit event
    e.preventDefault();
    // Give focus to next input element
    $(':input').eq($(this).index(':input') + 1).focus();
  }
});

小提琴

我最近也有同样的担忧,并为此创建了一个非常简单的jQuery插件

https://github.com/aymanrb/jquery-tabable-required

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM