0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

What if I want to add validation to only one input field in the form, say.. company_name? @Sadikhasan
Awesome. Fantastic. Excellent.
1

in add button click event :

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

good luck

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.