John John - 6 months ago 14
jQuery Question

how to add/remove tr in a table when checkbox is select/deselect in jquery

I want to add/remove a row in a table when selecting/deselecting a checkbox. The checkbox and table have the same value. For example if a checkbox has value of

2
, the specific row of the table has a value of exactly
2
, and so on.

To clarify better, if you select the checkbox of value
3
, it will add a
tr
in the table and show the value of
2
and if you deselect the checkbox of value
2
, it will remove the
tr
that contains value of
2
.

Below is my code. It works for adding but doesn't work for removing. Any help?

<table class="table table-hover table-striped" id="tbl">
<tr>
<td>value of 1</td>
<tr>
</table>

<input type="checkbox" name="id" value="1">
<input type="checkbox" name="id" value="2">
<input type="checkbox" name="id" value="3">


$('input[type="checkbox"]').change(function(){
if($(this).is(':checked')){
$('#tbl').append('<tr><td>' + $this.val() + '</td></tr>');
} else {
$('#tbl').find('<tr><td>' + $this.val() + '</td></tr>').remove();
}
});

Answer

It does work for removing. But you just fail to find the <tr> element. If I get you correctly, this code should work.

$('input[type="checkbox"]').change(function() {
    var val = $(this).val();
    if($(this).is(':checked')) {
        var $tr = $('<tr />').attr('data-val', val);
        var $td = $('<td><i class="fa fa-times" aria-hidden="true"></i></td>');

        $tr.append($td);
        $('#tbl').append($tr);
    }
    else {
        $('#tbl').find("[data-val='"+ val +"']").remove();
    }

 });
Comments