我在尝试复制一组字段时遇到问题。
例如我有
<div class="must_Duplicated ">
<div class="form-group">
<label >Name:</label>
<input type="text" class="form-control" name="study[0].name" >
</div>
<div class="form-group">
<label>Middle:</label>
<input type="text" class="form-control" name="study[0].Middle" >
</div>
<div class="form-group">
<label>Surname:</label>
<input type="text" class="form-control" name="study[0].surname" >
</div>
</div>
当我点击
时,我需要复制'must_Duplicated'类但想法是增加
study[0].name
study[0].Middle
study[0].surname
到
study[1].name
study[1].Middle
study[1].surname
等等
我尝试了很多方法,但是我找不到每次增加名称值的解决方案
上面的内容只是我的代码比这个
更长的例子答案 0 :(得分:0)
$("button").click(function(e){
var mdCopy = $('.must_Duplicated').clone();
$.each($(mdCopy).find('input'), function(){
var n = parseInt($(this).attr('name').match(/\d/g), 10);
var startString = $(this).attr('name').split("[")[0];
var endString = $(this).attr('name').split(".")[1];
//increment the number
n++;
//rebuild the string
$(this).attr('name', startString + "[" + n + "]." + endString);
});
//md_Copy now has updated inputs
console.log(mdCopy);
});
这将打破字符串,增加数字,然后将其重新组合在原始div的副本中 - 尽管这给出了格式
研究[1]。名称
研究[1] .Middle
研究[1] .surname
而不是问题中的1,2,3格式。希望这有帮助
答案 1 :(得分:0)
原生Javascript:
function duplicateForm() {
// get a copy of the first form which is as good as any.
var all_instances = document.getElementsByClassName("duplicate");
var first_instance = all_instances[0];
var clone_instance = first_instance.cloneNode(true);
// calculate the new index (just the number of existing instances of the form)
var new_index = all_instances.length;
// increment index of the study "array"
var new_inputs = clone_instance.getElementsByClassName("form-control");
for (var i = 0; i < new_inputs.length; i++) {
new_inputs[i].name = new_inputs[i].name.replace(/\[\d+\]/, "[" + new_index + "]");
}
// put new instance where you want it
document.body.appendChild(clone_instance);
}