8

I have a form which I want to validate using the jQuery Validation plugin. I currently have an issue with input element with array (name="inputname[]") which are created dynamically with jQuery .on(). Let me explain the issue:

  1. There is a form, with one input text exist named name[].
  2. There is a button to add more input texts, and this element executed with .on(). I clicked 2 or 3 times so there will be more than 1 input texts.
  3. I click submit, the form is correctly validate but it is only validate the first created array element and not the another element.

For full code I created a jsfiddle here: http://jsfiddle.net/ThE5K/4/

jQuery:

$(document).ready(function () {

    // MODE 1
    //   With [] or array name <<<< this one is not working
    $("#addInput").on('click', function () {
        $('#inputs').append($('<input class="comment" name="name[]" />'));
    });


    /* MODE 2
       Without [] or array name <<<< this one is working
       var numberIncr = 1;

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

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

        $('input.comment').each(function () {
            $(this).rules("add", {
                required: true
            })
        });

        event.preventDefault();

        console.log($('form.commentForm').valid());
    })

    $('form.commentForm').validate();
});

HTML:

<form class="commentForm">
    <div id="inputs"></div>
    <input type="submit" /> 
    <span id="addInput">add element</span>
</form>

I create two modes inside them, the working one (dynamic input text without array name) and the not working one (dynamic input text with array name).

I have been going though those solution but unfortunately no one of them worked:

Please help.

2
  • 1
    You are adding your rules when the form is submitted. This is all wrong. You should be adding your rules immediately after creating the new fields. Commented Jul 14, 2013 at 20:09
  • Please include enough code within OP to create a concise demo. Your OP should be fully "self-contained" and not be dependent upon external links. I've edited your OP to include the full code. Commented Jul 14, 2013 at 20:24

2 Answers 2

21

Regarding your code for creating the new fields:

// Mode 1
$("#addInput").on('click', function () {
    $('#inputs').append($('<input class="comment" name="name[]" />'));
});

The entire reason your "Mode 1" was not working is because you've assigned the same exact name attribute, name="name[]", to every single new input. The jQuery Validate plugin absolutely requires that every input element have a unique name attribute. Just use your numberIncr variable within name[] to ensure this unique name.

Also, you really should not be adding rules upon submit. The submit event is normally where all the rules are checked, so adding rules at this point does not make a lot of sense. The new rules should be added when the new input fields are created.

For your simple case, the rules('add') method is overkill for this anyway and you can totally eliminate your .on('submit') handler. Since the rule is required, you can simply add a class="required" to your new input elements.

Here is working code:

jQuery:

$(document).ready(function () {

    // MODE 1
    var numberIncr = 1;
    $("#addInput").on('click', function () {
        $('#inputs').append($('<input class="comment required" name="name[' + numberIncr + ']" />'));
        numberIncr++;
    });

    $('form.commentForm').validate();
});

DEMO: http://jsfiddle.net/ThE5K/6/

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Sparky, thank you for answer and warning. I never know there is a name[1], name[2] (number inside [] brackets). However, first I need to know how PHP process this variable, so I will try your code ASAP... Thanks.
Update: I am applying what do you suggest on my form, now everything works correctly (and perfectly) like a charm. I also able to eliminate .on(submit). Thanks!
@user9437856, please don't ask questions about your own question under answers elsewhere. Nobody looking at this has any idea about your project or "controller".
@Sparky, asked this because you tag me this question.
-1
    The validation can be simply done by class name
        <form action="http://xxxx/project/create" class="form-horizontal" id="invoice_form" method="post" accept-charset="utf-8">
            <table>
                <tr>
                    <td><input type="text" name="description[]" class="form-control validate_form" id="description"><span class="error">This field is required.</span></td>

                    <td><input type="text" name="per_litre[]" class="form-control validate_form validate_number per_litre"><span class="error">This field is required.</span><span class="error">Please enter number.</span></td>
                </tr>
                <tr>
                    <td><input type="text" name="description[]" class="form-control validate_form" id="description"><span class="error">This field is required.</span></td>

                    <td><input type="text" name="per_litre[]" class="form-control validate_form validate_number per_litre"><span class="error">This field is required.</span><span class="error">Please enter number.</span></td>
                </tr>
            </table>

            <button type="submit" id="invoice_submit" class="btn btn-primary">Submit</button>
        </form>

Add style to hide error message:
     <style type="text/css">
        .error {
            color: red;
            display: none;
        }
    </style>

 Script for validate form fields by class name

    <script>
        $(document).on('click', '#invoice_submit', function(e){
            e.preventDefault();
            i = 0;
            $(".validate_form").each(function() {
                var selectedTr = $(this);
                var value = $(this).val();
                if (!value) {
                    selectedTr.next("span").show();
                    i++;
                } else {
                    selectedTr.next("span").hide();
                }
            });

            $(".validate_number").each(function() {
                var selectedTr = $(this);
                var value = $(this).val();

                var filter = /^[0-9]+([,.][0-9]+)?$/g;
                if (value != '') {
                    if (!filter.test(value)) {
                        selectedTr.next("span").next("span").show();
                        i++;
                    } else {
                      selectedTr.next("span").next("span").hide();
                    }
                }
            });
            if (i == 0) {
                $('#invoice_form').submit();
            }
        });
    </script>

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.