我在这里找到了一个动态添加表单文本字段的代码。但是,我需要将标签添加到文本字段,每次添加新文本字段时,标签也会更改值,例如,增加1。我设法添加标签,但我的主要问题是: 1.每次添加新字段和标签时,如何使标签增加1 2.删除文本字段后,也可以删除标签。 我是Javascript的新手,所以详细解释会如此受欢迎。
Javascript代码:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var y = 2;
var labelHTML = '<label for="inputEmail3" class="col-md-4 control-label">'+ $y + '</label>';
var fieldHTML = '<div class="col-md-6"><input type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="remove-icon.png"/></a></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(labelHTML, fieldHTML); // Add field html
y++;
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
HTML代码:
<fieldset>
<legend>Question Options:</legend>
<div class="field_wrapper form-group">
<label for="inputEmail3" class="col-md-4 control-label">1</label>
<div class="col-md-6">
<input type="text" name="field_name[]" value=""/>
<a href="javascript:void(0);" class="add_button" title="Add field"><img src="add-icon.png"/></a>
</div>
</div>
</fieldset>
答案 0 :(得分:0)
首先,你需要在你的add函数中定义你的html,使它们彼此独特。
其次,您需要在删除输入字段及其父div之前删除IBOutlet
。
label
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var y = 2;
var x = 1; //Initial field counter is 1
var labelHTML = "";
var fieldHTML = "";
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
labelHTML = '<label for="inputEmail' + x + '" class="col-md-4 control-label">'+ 'test' + '</label>';
fieldHTML = '<div class="col-md-6"><input id="inputEmail' + x + '" type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="remove-icon.png"/></a></div>'; //New input field html
x++; //Increment field counter
$(wrapper).append(labelHTML, fieldHTML); // Add field html
y++;
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').prev().remove(); //Remove previous field html
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});