我有一个表单,您可以添加字段:http://jsfiddle.net/ytrkqr6a/2/
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control cameras" readonly /> <a href="#" class="remove-camera">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control cameras" readonly /></div>
</div>
一切正常,添加字段,但我挂断的地方是当你删除其中一个字段然后数字顺序下降..如何让它更新剩余的字段,以便每次添加时都保持正确的数字顺序或删除字段:
相机1
相机2
相机3
等...
提前致谢!
答案 0 :(得分:1)
我刚刚添加了一个jQuery&#34;每个&#34;每次单击删除链接时,循环到每个输入字段的placerholder,name和value。当使用每个传递给函数的值是循环当前迭代中的项的索引时,我使用变量elm。由于每个输入字段都使用camerasCounter进行分类,因此您可以使用$(this)轻松调用循环中的input元素。如果你问我,每个都是jQuery非常有用的部分。
http://jsfiddle.net/v76zn30o/2/
HTML
<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>
<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control camerasCounter" readonly /></div>
</div>
和jQuery
$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control camerasCounter" readonly /> <a href="#" class="remove-camera">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
$(".camerasCounter").each(function(elm){
x = elm + 1
$(this).attr({
"placeholder": "Camera " + x,
"name": "Camera " + x,
"value": "Camera " + x
});
});
});
});