Sam Young
Sam Young

Reputation: 183

jquery, remove table row when unchecked

I have a table with rows of data, when a user clicks on the row (tr) or the checkbox, it appends that row of data into another location. How do I make it that when a user unchecks from the original table AND the new appended row, that the row disappears?

I want it so that when the user unchecks from the original table, the appended row disappears. When the user unchecks from the appended row, only the appended row disappears.

// original table
<div id="searchsub">
 <table class="showsub">
    <tr class="datarow">
      <td>data</td>
      <td>data</td>
      <td>data</td>
    </tr>
 </table>
</div>

Row appends to this new table:

<table id="datarow">
</table>

Here's the jquery I have:

$(document).ready(function() {
        $("#searchsub table tr").click(function(event) {
            if(event.target.type !== 'checkbox') {
                $(":checkbox", this).trigger("click");
            }
        });

        $i = 1;
        $("input[type='checkbox']").change(function(e) {
            if($(this).is(":checked")) {
                $(this).closest("tr").addClass("highlightrow");
                var datarow = $(this).closest("tr.datarow");
                var row = datarow.clone();
                row.addClass("append" + $i);
                $("#submitshipment #datarow").append(row);
                $i++;
            } else {
                $(this).closest("tr").removeClass("highlightrow");
                $(".append").closest("tr").remove();
            }
        })
    })

Of course this way whenever the row is unchecked ALL of the rows are deleted, which isn't what I want. Please help?

EDIT: mark up of the appended row:

<tr class="datarow highlightrow append1">
    <td>120093</td>
    <td>G13</td>
    <td><input type="checkbox" class="searchsub" name="searchsub[]" value="1"></td>
 </tr>

jsFiddle:

http://jsfiddle.net/7cXqR/1/

Upvotes: 1

Views: 1287

Answers (1)

Stevangelista
Stevangelista

Reputation: 1829

Yes, unfortunately the non-functional jsFiddle doesn't really help ;-)

I think I've sorted out what you're trying to do though; the issue is you don't have anything (be it using jQ .data() or in markup) that relates your appended rows to your source rows. If you look at the jsFiddle I made (forked from yours) you'll see how I use the "value" attribute you have on the checkbox in the source table to find the cloned rows in the append table:

$('#datarow').find('input:checkbox[value="' + $(this).val() + '"]').closest('tr').remove();

http://jsfiddle.net/A4w59/

This approach could be modified to use any markup (stock or custom data-* attributes) or even jQ's .data() method; the key is being able to associate the source & append rows so that you can remove the appended row when unselecting it in the source table.

Upvotes: 1

Related Questions