I know there are some questions up which look like mine, but in this case I want the remove button to be removed as well and I don't know how I can do this.
Here is my question:
I append 3 elements with jQuery when an append button is clicked. Including a remove button.
I want this remove button to remove it self and the other two elements. The counter should make identical Id's, but i'm not sure if i did this right way with jQuery.
How can i delete three elements including the remove button onclick?
$(function() {
var counter = 0;
$('a').click(function() {
$('#box').append('<input type="checkbox" id="checkbox" + (counter) + "/>');
$('#box').append('<input type="text" id="t1" + (counter) + "/>');
$('#box').append('<input type="button" value="." id="removebtn" + (counter) + "/>');
$("#box").append("<br />");
$("#box").append("<br />");
counter++;
});
$('removebtn').click(function() {
remove("checkbox");
});
});
my suggestion would be like this.
$(function () {
var counter = 0;
$('a').click(function () {
var elems = '<div>'+
'<input type="checkbox" id="checkbox"' + (counter) + '" class="item"/>' +
'<input type="text" id="t1"' + (counter) + '"/>' +
'<input type="button" class="removebtn" value="." id="removebtn"' + (counter) + '"/>' +
'</div>';
$('#box').append(elems);
$("#box").append("<br />");
$("#box").append("<br />");
counter++;
});
$('.removebtn').live(function () {
$(this).parent().remove();
});
});
Suppose your remove button's id is #removebtn1234. Then
$("#removebtn1234").click(function(){
$(this).remove();
});
should work
But for easier manipulation on multiple items, I suggest you modify to following:
$('a').click(function() {
$('#box').append('<input type="checkbox" data-id="' + counter + '"/>');
$('#box').append('<input type="text" data-id="' + counter + '"/>');
$('#box').append('<input type="button" value="." class="removebtn" data-id="' + counter + '"/>');
$("#box").append("<br /><br/>");
counter++;
});
$(".removebtn").click(function(){
var id = $(this).data("id");
$("*[data-id=" + id + "]").remove();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With