我需要复制表格的行(在表格中)
在此处查看 jsbin:http: //jsbin.com/ExiRAMa/1/edit
标记:
<div id="o99_the_work">
<table><tbody>
<tr>
<!-- THE ORDER -->
<td>X</td>
<td class="small-text"><span class="wpcf7-form-control-wrap submitted-file"><input type="file" name="submitted-file" value="1" size="40" class="wpcf7-form-control wpcf7-file" id="submitted-file-1"></span></td>
<td><span class="wpcf7-form-control-wrap number-of-copies"><input type="text" name="number-of-copies" value="" size="40" class="wpcf7-form-control wpcf7-text small-text" id="number-of-copies-1"></span></td>
<td><span class="wpcf7-form-control-wrap checkbox-copy-type"><span class="wpcf7-form-control wpcf7-checkbox" id="copy-type-1"><span class="wpcf7-list-item"><input type="checkbox" name="checkbox-copy-type[]" value="color"> <span class="wpcf7-list-item-label">color</span></span><span class="wpcf7-list-item"><input type="checkbox" name="checkbox-copy-type[]" value="bw"> <span class="wpcf7-list-item-label">bw</span></span><span class="wpcf7-list-item"><input type="checkbox" name="checkbox-copy-type[]" value="transperant"> <span class="wpcf7-list-item-label">transperant</span></span><span class="wpcf7-list-item"><input type="checkbox" name="checkbox-copy-type[]" value="pergament"> <span class="wpcf7-list-item-label">pergament</span></span></span></span></td>
<td><span class="wpcf7-form-control-wrap submitted-remarks"><input type="text" name="submitted-remarks" value="" size="40" class="wpcf7-form-control wpcf7-text" id="submitted-remarks-1"></span> </td>
</tr></tbody></table>
<button id="add_row">Add new</button>
</div>
JS:
jQuery("#add_row").click(function() {
var row = jQuery("#k99_the_work tbody > tr:last"),
newRow = row.clone(true);
newRow.find("input[type=text],input[type=file]").each(function() {
var num = +(this.id.match(/\d+$/) || [0])[0] + 1;
this.id = this.id.replace(/\d+$/, "") + num;
this.name = this.id;
});
newRow.insertAfter(row);
return false;
});
正如您从 bin 中看到的那样,脚本在 input=text 上运行良好,并且它同时增加了 name 和 ID - 但我的问题是如何处理 checkboxes 。我需要增加名称、ID 等,同时保持单独的数组checkbox-copy-type[]
。意思是,复制后我需要checkbox-copy-type-1[]
等checkbox-copy-type-2[]
我绝不是一个正则表达式的人,但我尝试添加:
newRow.find("input[type=checkbox]").each(function() {
var num = +(this.id.match(/checkbox-copy-type/) || [0])[0] + 1;
// this.id = this.name.replace(/\[]/, "vv") + num;
this.id = this.name.replace(/\[]/, "") + num;// take off the brackets
this.id = this.name + "[]" ;// add the brackets again
this.name = this.id;
});
但是当我尝试这个时,我得到的只是另一组括号,例如checkbox-copy-type[][]
,checkbox-copy-type[][][]