idoxobi
idoxobi

Reputation: 23

Add validation rules using jquery validate plug-in on dynamically generated elements

I am trying to add some validation rules on an input created from html literals.

This is my fiddle: http://jsfiddle.net/idoxobi/HW4xY/1/

Html:

<form id='form' method='post' >
    <div id='details'>
    </div>
    <a id='Add' href='javascript:void()'>Add</a>
    <br />
    <input type='submit' />
</form>

JavaScript:

$(document).ready(function() {
    $('#form').validate();
    var input = "<input type='text' class='item' name='item' />";
    $('#Add').click(function() {
        $('#details').append(input+'<br />');
        $('#details input:last').rules('add', {
            required: true
        });
    });
})

It seems to recognize the rule just in the first element, but the others pass without validation.

Is the first time I use this plug-in, but in the forums everyone says this should work just fine.

Any suggestions?

Upvotes: 1

Views: 7234

Answers (2)

Manoj Yadav
Manoj Yadav

Reputation: 6612

Its because input field name is same for each, and it has been fixed by @YD1m, my method is as below:

$(document).ready(function() {
    $('#form').validate();
    var counter = 0;
    $('#Add').click(function() {
        counter++;
        $('#details').append("<input type='text' class='item required' name='item_" + counter + "' />" + '<br />');
    });
});

Upvotes: 0

YD1m
YD1m

Reputation: 5895

check this:

html:

<form id='form' method='post' >
    <div id='details'>
    </div>
    <a id='Add' href='#'>Add</a>
    <br />
    <input type='submit' />
</form>

js:

$(document).ready(function() {
    $('#form').validate();
    var i = 0;
    $('#Add').click(function() {

        var input = "<input type='text' class='item' name='item"+ i++ +"' />";
        $('#details').append(input+'<br />');
        $('#details input:last').rules('add', {
            required: true
        });

        return false;
    });
});

on jsfiddle

Upvotes: 1

Related Questions