parsh
parsh

Reputation: 756

How to validate dynamic sections of form using jquery validate

I created a JSFiddle. I am dynamically adding a div containing an input element (in real app there are multiple fields). When I click Submit, it just validates the first and not dynamically added HTML elements. I am making sure the dynamic elements have unique ids.

Any thoughts?

$('#submit').click(function (e) {    
    e.preventDefault();
    validator = $("#myForm").validate({
        rules: {
            name: "required"
        }
    });
    $("#myForm").valid();
});

Update:- I noticed something peculiar. After I add a new input element, and then focused on this new input and click submit, I can see in firebug, that jquery automatically adds a "class=error" to this input tag w/o showing the error message. And if i try writing something to the second input, it removes the error message from the first.

Upvotes: 2

Views: 1916

Answers (1)

politus
politus

Reputation: 6086

Changing your markup to this (your submit button was outside of the form tag)

<form id="myForm">
    <div id="section">
        <input type="text" name="name" class="required"/>
    </div>
    <input type="button" id="add" value="add" />
    <input type="submit" id="submit" value="submit" />
</form>

and inside your jQuery onready you have this

var count = 0;
$("#myForm").validate();
$('#add').on('click', function () {
    var section = $('#section').clone(false).attr('id', function () {
        return 'section' + (count);
    });
    section.find('input').attr('name', function () {
        return 'name' + (count);
    });
    section.find('label').attr('for', function () {
        return 'name' + (count);
    });
    section.insertAfter('#section');
    count++;
});

This gives you what you need:

  1. each input with a unique name
  2. the label matching the corresponding input field

updated fiddle here

Upvotes: 2

Related Questions