2

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?

Below are my codes:

<body>
    <section class="container">
        <div class="majors">
            <h1>Department</h1>
        </div>
        <form class="hform" id="selectForm" action="/action_page.php">
            <select name="Department">
                <option value="Sociology" selected>Sociology</option>
                <option value="Science">Science</option>
                <option value="Humanities">Humanities</option>
                <option value="Linguistics">Linguistics</option>
            </select>

            <div class="sbutton">
                <input type="button" id="submit_form" value="submit" />
            </div>
            <button class="delete" type="button" value="delete">Delete</button>
        </form>
    </section>

    <section class="container">
        <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
            <fieldset>
                <div class="form-copy-wrap">
                    <input class="checkbox" type="checkbox" />
                    <p>
                        <label for="aname">Name</label>
                        <input name="name[]" minlength="5" type="text" required/>
                    </p>
                    <p>
                        <label for="aemail">Email</label>
                        <input name="email[]" type="email" required/>
                    </p>
                    <p>
                        <label for="aage">Age</label>
                        <input name="age[]" type="number" required/>
                    </p>
                </div>
                <div class="input_fields_wrap">
                    <div class="addButton">
                        <button type="button" value="add">Add</button>
                    </div>
                </div>
            </fieldset>
        </form>
    </section>
    <script>
        $("#submit_form").on('click', function (e) {
            e.preventDefault();
            $("form#commentForm").submit();
            $(".form-copy-wrap").submit();
        });
        $("form#commentForm").validate({
            rules: {
                name: "required",
                email: {
                    required: true,
                    email: true,
                }
            },
            messages: {
                name: "Please specify your name",
                email: {
                    required: "We need your email address to contact you",
                    email: "Your email address must be in the format of [email protected]"

                }
            }
        });
    </script>

    <script>
        $(document).ready(function () {
            var max_fields = 10;
            var counter = 0;

            $('.addButton').on('click', function () {
                counter++;
                if (counter >= max_fields) {
                    console.log('You have reached a max limit fields')
                    return;
                }
                var copy = $('.form-copy-wrap').first().clone();

                $("#commentForm fieldset").append(copy);
            });

            $('.delete').on('click', function () {
                $('input:checkbox').each(function () {
                    if ($(this).is(':checked')) {
                        $(this).closest('.form-copy-wrap').remove();

                    }
                });
            });
        });
    </script>
</body>
5
  • It's not an answer, but I'm wondering why 2 script tags? Commented Jul 11, 2017 at 9:59
  • One for the validation the other for adding dynamically created fields. better to write both inside one? Commented Jul 11, 2017 at 10:03
  • @BibekSharma You can add rules for dynamically added inputs and check form before form submission with $('form.commentForm').validate().form() Commented Jul 11, 2017 at 11:11
  • @BibekSharma yes, as far as I know, there is no benefit to write each piece of code in extra script tag, actually there is no need to open script tag for each job. Commented Jul 11, 2017 at 11:33
  • @BibekSharma did you solve the problem? Commented Jul 11, 2017 at 19:23

2 Answers 2

2

Please replace click event with this one

 $('.addButton').on('click', function () {
    counter++;
    if (counter >= max_fields) {
       console.log('You have reached a max limit fields')
       return;
    }
    var copy = $('.form-copy-wrap').first().clone();

    $("#commentForm fieldset").append(copy);

    var form = $("#commentForm");
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(document);
});
Sign up to request clarification or add additional context in comments.

2 Comments

sorry, but do you mean this click event below that I should replace with the codes above? $('.addButton').on('click', function () { counter++; if (counter >= max_fields) { console.log('You have reached a max limit fields') return; } var copy = $('.form-copy-wrap').first().clone(); $("#commentForm fieldset").append(copy); });
Keep your addButton function as it is. Just copy last four line from my code and paste into your function. It will work to validate dynamically added controls. Also please change form id if it is different then I mention in my code.
1

You can validate your form before form submission and implement validation for dynamically added input. Add rules for each ot them with jquery $.each and implement validation like following.

$(document).ready(function() {          
        var inputCount = 1; // used to increment the name for the inputs

        function addInput() {
            $('.form-copy-wrap').append($('<p>New Input: <input class="required" name="name'+inputCount+'" /></p>'));
            inputCount++;
        }

        $('form.commentForm').on('submit', function(event) {
            // adding rules for inputs with class 'required'
            $('#inputs input.required').each(function() {
                $(this).rules("add", 
                    {
                        required: true
                    })
            });            

            // test if form is valid 
            if($('form.commentForm').validate().form()) {
                console.log("valid");
            } else {
                // prevent default submit action
                event.preventDefault();
                console.log("not valid");
            }
        })

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

        // initialize the validator
        $('form.commentForm').validate();

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form class="commentForm" method="get" action="" style="float:left">
    <div>
         <div class="form-copy-wrap">
            <input class="checkbox" type="checkbox" />
            <p>
                <label for="aname">Name</label>
                <input name="name[]" minlength="5" type="text" required/>
            </p>
            <p>
                <label for="aemail">Email</label>
                <input name="email[]" type="email" required/>
            </p>
            <p>
                <label for="aage">Age</label>
                <input name="age[]" type="number" required/>
            </p>
         </div>

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

    </div>
</form>

1 Comment

Your snippet is working perfectly. But how can I access form data in the process.php page?

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.