我有基本的javascript代码来生成输入文本区域,如下所示
$("#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);
});
我有一个动态字段的表单。我正在为其他元素使用jquery验证器。现在我还要验证这个动态创建的字段。
对于静态字段,我的工作验证脚本。
$('#frm_register').validate({
focusInvalid: false,
ignore: "",
rules: {
FirstName: {
required: true
} ....
这里是我动态字段的示例。
<input type="text" id="InvoiceNumber_0__InvoiceNumber" placeholder="Fatura Numarası" name="[0].InvoiceNumber">
<input type="text" id="Interests_0__InterestText" placeholder="Fatura Tutarı(TL)" name="[0].Amount">
<input type="text" id="InvoiceNumber_1__InvoiceNumber" placeholder="Fatura Numarası" name="[1].InvoiceNumber">
<input type="text" id="Interests_1__InterestText" placeholder="Fatura Tutarı(TL)" name="[1].Amount">
答案 0 :(得分:1)
您可以在创建新输入元素后立即使用the .rules('add')
method ...
$("#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
});
});
或者,对于像required
这样的简单规则,您可以在创建新元素时将required="required"
属性添加到新元素中...
$("#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);
});