Jquery Validation for Dynamically Created Fields

前端 未结 1 1983
生来不讨喜
生来不讨喜 2020-11-29 13:02

I have basic javascript code to generate input text areas as below

$(\"#btnAdd\").click(function (e) {
        var itemIndex = $(\"#container input.iHidden\         


        
相关标签:
1条回答
  • 2020-11-29 13:40

    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);
    });
    
    0 讨论(0)
提交回复
热议问题