JQuery validation with fields that are dynamically added to the form

I have the following form:

<form class="form-validation">
  <input name="product[0][name]" id="form_product[0][name]" data-rule-required="true">
</form>

which is checked using the jQuery validation plugin. I call it this way:

$(".form-validation").validate();

Validation works as expected. Then I have a button that dynamically adds fields to the form, basically it creates this:

<form class="form-validation">
  <input name="product[0][name]" id="form_product[0][name]" data-rule-required="true">
  <input name="product[1][name]" id="form_product[1][name]" data-rule-required="true">
  <input name="product[2][name]" id="form_product[2][name]" data-rule-required="true">
  ...
</form>

Now after that, validation no longer behaves normally. He is still validating the form, but I am getting strange results. Sometimes the onsubmit value from filed3 is moved to field2, and rules are also passed between fields.

I think I will need to tell the validator that new fields have been added, but I don’t know how?

+5
source share
3 answers

, rules('add') . - , , .

, HTML, , :

http://jsfiddle.net/WVbmj/


OP:

, . from filed3 2, .

, , id, id="form_product[1][name]", input. id , . , .

, id: http://jsfiddle.net/WVbmj/ strong >

+4

,

.

<input id="Name" name="Name" type="text" class="netEmp form-control">

http://www.dotnetqueries.com/Article/136/jquery-validate-dynamically-added-fields

0

You must set the class name for all fields.

For instance:

<input class="form-control amount validate_form" name="amount[]" type="text">
<p class="validateError" style="color:red;display:none;">please enter amount.</p>
<button type="submit" id="fees_stream_submit" class="btn btn-primary">Submit</a>

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

                if (i == 0) {
                    $('#fees_stream_form').submit();
                }
            });
        </script>
0
source

All Articles