John John - 1 year ago 143
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

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

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

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">
<td>value of 1</td>

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

$('#tbl').append('<tr><td>' + $this.val() + '</td></tr>');
} else {
$('#tbl').find('<tr><td>' + $this.val() + '</td></tr>').remove();

Answer Source

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>');

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download