Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements onclick (including the remove button itself) with jQuery

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");
    });
});
like image 714
Opoe Avatar asked Dec 17 '10 09:12

Opoe


2 Answers

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();   
    });
});

simple demo

like image 188
Reigel Avatar answered Oct 12 '22 14:10

Reigel


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();
});
like image 36
xandy Avatar answered Oct 12 '22 15:10

xandy