Jquery Validation for Dynamically Created Fields

You could use the .rules('add') method immediately after the new input element is created…

$("#btnAdd").click(function (e) {
    var itemIndex = $("#container input.iHidden").length;
    e.preventDefault();
    var newItem = $("<span class="badge badge-success">" + itemIndex + "</span> <input id='Interests_" + itemIndex + "__Id' type="hidden" value="" class="iHidden"  name="Interests[" + itemIndex + "].Id" /><input type="text" id='InvoiceNumber_" + itemIndex + "__InvoiceNumber' placeholder="Fatura Numarası" name="[" + itemIndex + "].InvoiceNumber"/>    <input type="text" id='Interests_" + itemIndex + "__InterestText' placeholder="Fatura Tutarı(TL)" name="[" + itemIndex + "].Amount"/> <br /><br />");
    $("#container").append(newItem);

    // add the rules to your new item
    $('Interests_' + itemIndex + '__Id').rules('add', {
        // declare your rules here
        required: true
    });
});

Alternatively, for a simple rule like required, you could just add the required="required" attribute to the new element when you create it…

$("#btnAdd").click(function (e) {
    var itemIndex = $("#container input.iHidden").length;
    e.preventDefault();
    var newItem = $("<span class="badge badge-success">" + itemIndex + "</span> <input id='Interests_" + itemIndex + "__Id' type="hidden" value="" class="iHidden"  name="Interests[" + itemIndex + "].Id" /><input type="text" id='InvoiceNumber_" + itemIndex + "__InvoiceNumber' placeholder="Fatura Numarası" name="[" + itemIndex + "].InvoiceNumber"/>    <input type="text" id='Interests_" + itemIndex + "__InterestText' placeholder="Fatura Tutarı(TL)" name="[" + itemIndex + "].Amount" required='required' /> <br /><br />");
    $("#container").append(newItem);
});

Leave a Comment