0

Adding table row dynamically based on some count

        var del_count=$("#trainee_count").val();
        var row_counter=0;
        for(var i=0;i<del_count;i++){
        row_counter++;
        $(".add_trainee").append(   
            '<tr>'+
                '<td><input type="text" name="name"  class="required"  /></td>'+
                '<td><input type="text" name="jobTitle"  /></td>'+
                '<td><input type="text" name="email"  id="email" class="required email"  /></td>'+
                '<td><input type="text" name="phone" class="required phone"   /></td>'+
                '<td  class="my_laptop" align="center" valign="middle"><input type="checkbox" class="laptop_checkbox"   name="isLaptopRequired.'+row_counter+'"  checked /></td>'+
            '</tr>' 

            );
        }

Basically I am trying do the validation for multiple element with same name.

validation:

    $(".traineeDetailsForm").validate({ 
                errorContainer: "#error_div",
                errorPlacement: function(error, element) {}
            });

i may have 'n' number of rows , that will have 'n' number of elements with same name Here validation applies for only the first row(tr)

Sparky
  • 98,165
  • 25
  • 199
  • 285
monda
  • 3,809
  • 15
  • 60
  • 84

2 Answers2

1

You cannot validate multiple inputs sharing the same name. The jQuery Validate plugin requires that every input contain a unique name because the name is how the plugin keeps track of the inputs.

The solution is simply to use a counter as part of the name ensuring that it's unique, just like you did with your checkbox...

$(".add_trainee").append(   
        '<tr>'+
            '<td><input type="text" name="name' + count + '"  class="required"  /></td>'+
            '<td><input type="text" name="jobTitle' + count + '"  /></td>'+
            '<td><input type="text" name="email' + count + '"  id="email" class="required email"  /></td>'+
            '<td><input type="text" name="phone' + count + '" class="required phone"   /></td>'+
            '<td  class="my_laptop" align="center" valign="middle"><input type="checkbox" class="laptop_checkbox"   name="isLaptopRequired.'+row_counter+'"  checked /></td>'+
        '</tr>' );

Also see this answer: https://stackoverflow.com/a/18905194/594235

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
-1

Use .each() to validate multiple element with the same name.

$(".traineeDetailsForm").each(function () {
     $(this).validate({ 
          errorContainer: "#error_div",
          errorPlacement: function(error, element) {}
     });
});
Shri
  • 141
  • 2
  • 10