0

I am using jquery validation plugin and it is not applied on dynically added rows my code is:

Html:

<form action="test.php" onsubmit="return false;">
    <div id="add_rows"> 
        <div class="new-row">
            <input type="text" required="required" name="qty[]" /><br />
            <textarea required="required" name="test[]" rows='4' cols='15'></textarea>
        </div>
    </div>
    <button>Add</button>
</form>

Script:

var frm=$('form').validate({
    submitHandler: function(form) {
        // do other stuff for a valid form
        alert('form submitted');
        return false;
    }
});

$('button').on('click',function(){
    $clone=$('.new-row:first').clone();
    $clone.find('input,textarea').val('');      
    $clone.insertAfter($('.new-row:last'));
    $clone.find('input,textarea').rules('add',{required:true});
    $('.new-row:last').find('input,textarea').rules('add',{required:true});
});

Fiddle

Another issue, I have tried it on my system and I got error like : TypeError: e is null for the line $clone.find('input,textarea').rules('add',{required:true}); if I remove then error not comes, but this error is not seen in fiddle

1
  • jQuery Validate plugin requires that you must have unique name attributes on each input to be validated. Otherwise, there is nothing wrong with the way you've implemented rules('add'). Commented Jun 26, 2013 at 13:31

1 Answer 1

2

Try this, i think this is what you wanted

Added unique name to the textarea and input.

var incr = 0;
$('button').on('click',function(){
    incr++;
    $clone=$('.new-row:first').clone();
    $clone.find('input,textarea').val('');
    $clone.find('input').attr('name','qty'+incr+'[]');
    $clone.find('textarea').attr('name','test'+incr+'[]');

Demo here

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

5 Comments

Your code gives error TypeError: $.data(...) is undefined, plz check in console, also here the validation not working. It is HTML5 required whick makes the border red.
Ah, i see checking it out now
@RohanKumar You can check this one out, jsfiddle.net/YjgQ6/4 what i did is added a unique name for each textarea and input
@Anton Not suited. This data is stored in database after post. So, at server side how can I get different post variables? Thats why I created array of elements like qty[].
I'm not sure, might be possible to have qty[] in another attribute? <input type="text" name="input1" required="required" data="qty[]"/>

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.