繁体   English   中英

jQuery:根据name属性的开头和结尾选择元素

[英]jQuery: selecting elements according to the beginning and the end of the name attribute

我有以下代码:

  <script>
  $(document).ready(function(){
  $('form').validate({

    //rules: { 'input_name': { email: true} },
    rules: { 'name^=input', 'name$=jander': { email: true} },
    messages: { 'input_name': "Jar" },

    errorPlacement: function(error, element) {
     error.insertBefore(element);
    },
    debug:true

    })

  });
  </script>

 </head> 

  <body>
<div id="jar">fasdf</div>

<form id="clar">
<p id="my_paragraph">Escribe ALGO para que haga la validacion de email</p>
<input name='input_jander' type="text" ">
<input type="submit" >

</form>

如您所见,我尝试将验证规则应用于其name属性以“ input”开头以“ jander”结尾的所有输入字段,但是它不起作用(错误消息未显示)。

只需提供您想要以某个类作为目标并以这种方式作为目标的输入即可。 为什么要加重自己的负担

这些键只是映射到表单的name属性。

但是,我以前曾经遇到过这个问题,所以我就这样解决了...

var rules = {},
    messages = {},
    inputs = $(':input[name^="input"]').filter(':input[name$="jander"]');

inputs.each(function() {
   var name = $(this).attr('name');
   rules[name] = { email: true };
   messages[name] = { email: 'Type a proper email, mate!' };
});

$('form').validate({
    'rules': rules,
    'messages': messages
});

jsFiddle input元素被匹配。

尽管您可能应该为这些元素提供更清晰的标识符。

暂无
暂无

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

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