Reputation: 2005
I have implemented jquery clone and remove. When ADD button is clicked a DIV A with certain form elements are cloned and inserted into another DIV B. In DIV A there is a hidden form button REMOVE. Now I require to enable the REMOVE button only in the clones when ADD button is clicked. i.e; I want to keep the form element in DIV A always hidden.
This is my code.
<div class="rule" id="rule">
<div class="fm-req">
<select name="rulefield" id="rulefield">
<option value="">select</option>
</select>
</div>
<div class="fm-opt" >
<input type="button" class='remove' value="-" style="display:none;"/>
</div>
</div>
<div class="fm-rulebutton">
<input type="button" id="addButton "class='add' value="+"/>
</div>
<div id='TextBoxesGroup' class="group">
here Div 'rule' is cloned into Div 'TextBoxesGroup'
$(document).ready(function() {
var id = 0;
$('.add').click(function(){
id++;
$('.fm-opt').children('.remove').show();
var prot = $(document).find(".rule").clone();
prot.attr("class", 'rule'+id)
prot.find(".id").attr("value", id);
$(document).find("div .group").append(prot);
});
$('.remove').live("click", function(){
$(this).closest("#rule").remove();
});
});
Upvotes: 2
Views: 9490
Reputation: 1919
$('.add').click(function(){
id++;
$('.fm-opt').children('.remove').show();
var prot = $(document).find(".rule").clone();
prot.attr("class", 'rule'+id)
prot.find(".id").attr("value", id);
$(document).find("div .group").append(prot);
});
should be changed as,
$('.add').click(function(){
id++;
var prot = $(document).find(".rule").clone();
prot.attr("class", 'rule'+id)
prot.children('.remove').show();
prot.find(".id").attr("value", id);
$(document).find("div .group").append(prot);
});
You should make visible only those buttons which have been cloned.
Upvotes: 3
Reputation: 48435
The problem is you are calling .show()
for all remove buttons. You need to limit it to only the new clone element. Like so:
$('.add').click(function(){
id++;
var prot = $(document).find(".rule").clone();
prot.attr("class", 'rule'+id)
prot.find(".id").attr("value", id);
prot.find('input.remove').show();//<-- this is the important part
$(document).find("div .group").append(prot);
});
This code will now only call .show()
on the remove button that is found within the newly cloned element
Upvotes: 3
Reputation: 179
While cloning add unique Id="" value for cloned element.
In remove method, you can easily access the unique element and remove it.
Upvotes: 0