我正在使用按钮单击创建多个文本字段,但无法为每个字段创建唯一的ID。这是我的代码:
<div class="form-group" id="intro-box">
<input type="text" style="width:85%;float:left;margin-bottom:5px;" class="form-control" id="introlabelname0" name="introlabelname" placeholder="Label Name" value="">
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(1);">
</div>
<script>
function addMore(i) {
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
}
</script>
最初的id是introlabelname0
在创建多个字段时应使用的ID introlabelname1,introlabelname2...
,依此类推。同样,当用户单击-
按钮时,所有ID也应像一样依次出现introlabelname0,introlabelname1,introlabelname2...
。
这是我的全部Plunkr代码。
试试这个 -
<script>
var a = 0;
function addMore(i) {
a = a + 1;
i = a;
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function updateIds(){
var textboxElements = $('#intro-box input:text');
for(var j = 0; j < textboxElements.length; j++) {
$('#intro-box input:text')[j].id = "introlabelname" + j;
console.log($('#intro-box input:text')[j].id);
}
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
updateIds();
}
</script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句