【发布时间】:2014-11-26 14:48:43
【问题描述】:
我正在动态添加按钮,它可以通过这段代码完美添加,当我想删除用户通过单击添加更多按钮创建的文本框时效果很好。
在点击事件中完美添加和删除按钮的代码。
这里是 jquery 脚本!。
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div class="controls"><input type="text" class="form-control" name="sub-category-name[]" required/><a href="#" class="removeclass">×</a></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
这里是 Html。
<div class="form-group" id="InputsWrapper">
<label for="sub-category-name">Sub Category Name </label>
<div class="controls">
<input type="text" class="form-control" id="typeahead" name="sub-category-name[]" required>
<a href="#" id="AddMoreFileBox" class="btn btn-info">Add More Field</a>
</div>
</div>
但是当我稍微更改代码结构时,用户可以添加文本框但无法删除动态添加的文本框。
这是 Html 代码。
<div class="form-group" id="InputsWrapper">
<div class="input-group"><input type="text" class="form-control">
<span class="input-group-btn"> <a href="#" id="AddMoreFileBox"><button class="btn btn-default" type="button">+</button></a> </span>
</div>
</div>
这是脚本。
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div class="input-group"><input type="text" class="form-control"><span class="input-group-btn"> <a href="#" class="btn btn-default removeclass">X</a></span</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
【问题讨论】:
-
创建一个jsfiddle.net - 注意在fiddle中使用“head”而不是“onload”
-
并验证您的 HTML。 A 不应该包装一个按钮
标签: javascript jquery html