Udenewu Kingsley
Udenewu Kingsley

Reputation: 1

Validating Dynamic input fields with jquery

Hey guys i'm trying to validate input fields that will be dynamically generated by the user with a link button to make the user add more input fields but the problem i have is that its only the first field that is validated but the input fields generated dynamically doesn't validate.
Here's the html codes:

<form id="testform" method="post">
    <div style="margin-top: 10px;" id="within_nigeria1">
        <div id="divint1">Address(s) within Nigeria: <a href="" id="add_field_button">Add more field</a>

            <input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text[]" />
            <div class="wn"></div>
        </div>
    </div>
    <input type="submit" value="submit" />
</form>

Here is the jquery codes:

$('#testform').validate({
    rules: {
        "address_text[]": {
            required: true
        }
    }
});

var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#within_nigeria1"); //Fields wrapper
var add_button = $("#add_field_button"); //Add button ID
var wrapper1 = $(".wn");


var x = 1; //initlal text box count
$(add_button).click(function (e) { //on add input button click
    e.preventDefault();

    if (x < max_fields) { //max input box allowed
        x++; //text box increment
        $(wrapper1).append('<input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text[]"/><a href="" class="remove_field">Remove</a>');
    }
});

$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;


});

Upvotes: 0

Views: 1437

Answers (1)

Barmar
Barmar

Reputation: 780974

jquery.validate requires that every input have a unique name. So instead of having names like

name="address_text[]"

you need to put explicit counters into the brackets. The initial HTML should use name=address_text[0], and the Javascript that adds rows can increment it.

var counter = 0;

$(add_button).click(function (e) { //on add input button click
    e.preventDefault();

    if (x < max_fields) { //max input box allowed
        x++; //text box increment
        counter++;
        $(wrapper1).append('<input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text['+counter+']"/><a href="" class="remove_field">Remove</a>');
    }
});

Upvotes: 1

Related Questions