我正在动态添加按钮,并且可以完美地添加此代码,当我想删除用户创建的文本框时,点击添加更多按钮可以完美无缺。
按钮在点击事件中完美添加和删除的代码。
这是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;
})
});
答案 0 :(得分:1)
您需要按标记和/或班级名称定位您的父母:
$(this).closest("div").remove(); // walk up the DOM until the nearest DIV
或
$(this).closest("div.form-group").remove(); // walk up to nearest div.form-group
如果我的容器错误
,请将form-group更改为要删除的容器的类答案 1 :(得分:0)
您需要:
$(this).parent().parent().remove();
在第二个列表中,您更改了结构HTML,但忘记了JS。
你的HTML是:
div
a.removeclass
您将监听器添加到a.removeclass,然后向前走DOM-tree:
$(this).parent('div').remove();
您的HTML现在:
div
span
a.removeclass
现在,如果你想删除div,你需要走两次树,但是一次!