我做了一个动态表单,但是当我动态地插入字段时,名称和ID没有正确更改。如何设置ID和名称值?
这里是我的代码:
<div id="dataRows">
<div class="fieldRow" id="template">
<select class="items" name="items{{counter}}" id="items{{counter}}" style="width:127px; float:left;"><option value="1" selected="selected" disabled="disabled"></option></select>
<textarea name="description{{counter}}" id="description{{counter}}" class="description" style="float:left; display: block; height: 30px; width:209px; border-radius:0px; margin: -1px 1px 0;"></textarea>
<input type="text" name="unitprice{{counter}}" id="unitprice{{counter}}" class="unitprice" style="float:left; display: block; height: 30px; width:106px; border-radius:0px; margin: -1px -1px 0;">
<input type="text" name="quantity{{counter}}" id="quantity{{counter}}" class="quantity" style="float:left; display: block; height: 30px; width:64px; border-radius:0px; margin: -1px 1px 0;">
<select name="firsttax{{counter}}" id="firsttax{{counter}}" style=" float:left; display: block; height: 31px; width:106px; border-radius:0px; margin: -2px -1px 0;"><option value="1" selected="selected" ></option></select>
<select name="secondtax{{counter}}" id="secondtax{{counter}}" style="float:left; display: block; height: 31px; width:107px; border-radius:0px; margin: -2px 0px 0;"><option value="1" selected="selected"></option></select>
<input type="text" name="linetotal{{counter}}" id="linetotal{{counter}}" class="linetotal" placeholder="0.00" readonly style="float:right; display: block; height: 31px; width:107px; border-radius:0px; background-color: #F0F0F0; text-align:right; margin: -31px -1px 0;">
<input type="button" class="button remove" id="btnDel" value="Remove Row" style="float:right; margin:-29px -110px; color: #ffffff; background-color: #d9534f; border-color: #d43f3a; padding: 3px 10px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; border:1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;" />
</div>
</div>
,这里是我的动态领域的Java脚本代码:
jQuery(document).on("ready", function() {
initAddRows();
});
function initAddRows() {
var template = jQuery("#template"),
dataRows = jQuery("#dataRows")
jQuery("#btnAdd").on("click", function() {
var newRow = template.clone(true, true),
fieldRows = dataRows.find(".fieldRow"),
rowNumber = fieldRows.length + {
{
counter
}
};
newRow.attr('id', 'row' + rowNumber).find('[id]').each(function() {
jQuery(this).attr("id", jQuery(this).attr("id") + rowNumber);
jQuery(this).attr("name", jQuery(this).attr("name") + rowNumber);
$('#itemscounter').val(+rowNumber);
});
fieldRows.filter(":last").after(newRow);
});
}
我的字段值items9,description9和我的{{计}} = 9 ,当我生成字段的字段名称是items910,description910,但我想名称和id是items10,description10。
我该怎么做?
总是JS做一些特定的事情! – Overcode
最好不要使用增量名称和id属性,因为它变成了维护地狱。将名称更改为'name []'并将值作为数组传递,并将id更改为类,以便可以对元素进行分组,然后在jQuery中根据需要遍历它们。 –