0

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--;


});
2
  • Do not use the same "id" attribute multiple times. Commented Dec 27, 2014 at 15:45
  • Thank you Mr Barmar I've done as you said but still yet i'm not able to validate the dynamic inputs fields generated by the user Commented Dec 27, 2014 at 23:09

1 Answer 1

1

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>');
    }
});
Sign up to request clarification or add additional context in comments.

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.