无法为动态生成的输入字段添加 jQuery 验证?

Unable to add jQuery validation for dynamically generated input fields?

我有一些输入字段是根据 jQuery 中的单击事件在单击按钮时动态生成的。我正在尝试向这些输入字段添加客户端验证。

但问题是,由于用户可以动态添加任意数量的输入字段,输入字段的id和名称是不同的。这样做是为了方便地在服务器端获取值。

因此在第一次点击时,输入字段的 ID 和名称将分别为 company_name0、emp0、offc_email0。在第二次单击时,它将添加一组新的输入字段以及已经存在的字段,名称和 ID 将变为 company_name1、emp1、offc_email1 等等。

验证码:

$('#frm_members').validate(
 {
  rules: {
    company_name: {
         required: true
      }, 
     emp :{
          number:true
     },

    offc_email:{
        email: true
    }
   }
}); 

这是一个 fiddle,其中包含部分工作演示,并且具有 html 和其他必要的 jquery 动态生成字段所需的代码。

add button点击事件中:

$("form").on("click", "#add_company", function (e) {    
    $('.addcomp').each(function () {
        $(this).rules("add", {
            required: true
        });
    });
});

祝你好运

您需要以下代码 click 函数

$("#add_company_div"+ i +" .input-sm").each(function(){
    $(this).rules("add", {
          required: true
    });
});

Demo

编辑

$("#add_company_div" + i+" .input-sm").each(function(){
      if($(this).attr("id").indexOf("company_name")>=0)
       {
           $(this).rules("add", {
              required: true
            });
       }
});

Demo