【问题标题】:How to create Rules for dynamically generated fields如何为动态生成的字段创建规则
【发布时间】:2015-03-10 07:48:52
【问题描述】:

http://www.kosherjellyfish.com/test/index.php

我正在为我的表单使用 [jQuery Validation Plugin][1]。

我在表格中有动态生成的表单字段:表格的数量取决于用户创建的数量。下表示例:

<?php (for $i=1;$i<3;$i++){?> 
<table class="coauthortable">

    <tr>
       <td>Title * </td>
       <td>
          <select name="contactTitle<? echo $i;?> ">
          <option value="">Select Title</option>
          <option value="Dr">Dr</option>
          <option value="Miss">Miss</option>
          <option value="Mr">Mr</option>
          <option value="Mrs">Mrs</option>
          <option value="Ms">Ms</option>
          <option value="Professor">Professor</option>
         </select>
      </td>
    </tr>

    <tr>
      <td>First Name *</td>
      <td><input type="text" name="contactFirstName<? echo $i;?>" style="width:280px;" /></td>
    </tr>


    <!--Actual program has more rows-->

</table>
<?php }  ?>                     

我希望将验证规则添加到动态生成的输入字段中:似乎我无法在验证方法本身中正确执行此操作,因为我不知道将要生成的实际字段数:

$("#papersubmitform").validate(
        {
        rules:{
            //Can't add rules this way as I do not know how many rows will be generated. 
            contactTitle: {required: true},
            contactFirstName: { required:true},

});

我尝试添加将在页面加载后添加到 $(document).ready(function() 的规则,但它似乎不起作用。

$(document).ready(function() {
   $(".coauthortable").each(function(i){ 
            $(this).find(":input").each(function(){ 
                $(this).rules("add",{required:true});
            });         
});

  $("#papersubmitform").validate();         


}); 

是否有人对我应该如何将规则添加到动态创建的元素有任何建议?

我已经在我自己的服务器中创建了一个示例页面...http://www.kosherjellyfish.com/test/index.php

【问题讨论】:

    标签: php jquery validation jquery-plugins


    【解决方案1】:

    您只需要按相反的顺序执行此操作:

    $(document).ready(function() {
       $("#papersubmitform").validate();         
    
       $(".coauthortable").each(function(i){ 
                $(this).find(":input").each(function(){ 
                    $(this).rules("add",{required:true});
                });         
        });
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2021-05-27
      相关资源
      最近更新 更多