Rav Rav - 1 year ago 179
jQuery Question

Validate Dynamically Added Input fields

I have used this jquery validation plugin for the following form.

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>




function addInput() {

var obj = document.getElementById("list").cloneNode(true);



<form id="commentForm" method="get" action="">

<p id="parent">

<input id="list" class="required" />

<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />


When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...

Answer Source

You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.

And here is my solution that I've tested and it works:

<script type="text/javascript">
   $(document).ready(function() {
        var numberIncr = 1; // used to increment the name for the inputs

        function addInput() {
            $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));

        $('form.commentForm').on('submit', function(event) {

            // adding rules for inputs with class 'comment'
            $('input.comment').each(function() {
                        required: true

            // prevent default submit action         

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
            } else {
                console.log("does not validate");

        // set handler for addInput button click
        $("#addInput").on('click', addInput);

        // initialize the validator



And the html form part:

<form class="commentForm" method="get" action="">

        <p id="inputs">    
            <input class="comment" name="name0" />

    <input class="submit" type="submit" value="Submit" />
    <input type="button" value="add" id="addInput" />


Good luck! Please approve answer if it suits you!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download