version 2
version 2

Reputation: 1059

Unable to add jQuery validation for dynamically generated input fields?

I have a few input fields which are generated dynamically upon a button click based on the click event in jQuery. I am trying to add client side validation to those input fields.

But the problem is, as the user can add any number of input fields dynamically, the id & name of the input fields are different. It's done that way so as to fetch values in server side easily.

So on the first click, the id & name of the input fields will be company_name0, emp0, offc_email0 respectively. On the second click it will add a new set of input fields along with the already existing fields & the name & id will become company_name1, emp1, offc_email1 & so on.

Validation code:

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

    offc_email:{
        email: true
    }
   }
}); 

Here's a fiddle which contains a partial working demo & has html & other necessary jquery code necessary for dynamic generation of fields.

Upvotes: 0

Views: 2262

Answers (2)

Sadikhasan
Sadikhasan

Reputation: 18601

You need to following code click function

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

Demo

Edit

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

Demo

Upvotes: 1

Hamix
Hamix

Reputation: 1335

in add button click event :

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

good luck

Upvotes: 1

Related Questions