user081608 user081608 - 7 months ago 7
Javascript Question

Using .closest within a table to hide a row

I am currently working on a table that expands details on a click of a row. Once a row is clicked, I want the hidden

<tr>
below it to show. I get that working correctly but when I try to hide it again, a white box appears below that I do not want to occur. Here is a fiddle of my example: https://jsfiddle.net/pt0skyyb/

HTML:

<table class="table">
<tr>
<th>Details</th>
<th>First</th>
<th>Second</th>
</tr>
<tr>
<td>+</td>
<td>First</td>
<td>Second</td>
</tr>
<tr class="child">
<td colspan="3">
<table class="child-table">
<tbody>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</td>
</tr>

<tr>
<td>+</td>
<td>Third</td>
<td>Fourth</td>
</tr>
<tr class="child">
<td colspan="3">
<table class="child-table">
<tbody>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>


JS:

$(function() {
$("td[colspan=3]").find("table").hide();

$("table").click(function(event) {
event.stopPropagation();
var $target = $(event.target);
if ( $target.closest('tr.child').hasClass("shown")) {
$target.closest('tr').find('.child').hide();
$target.closest("tr").find('.child').removeClass("shown");
} else {
$target.closest("tr").next().show();
$target.closest("tr").next().addClass("shown");
$target.closest("tr").next().find("table").slideToggle();
}
});
});


If you look at the html, the
<tr>
with class
child
is set to
display:none;
to begin with so it is hidden. Once you click the row to make it appear and then again to disappear, it is not being completely hidden and leaves a white box. I am trying to make it disappear fully as it was before it was clicked.

To do this, I am trying
$target.closest('tr').find('.child').hide();
to hide it, but I can't get it to work correctly. Right now it is never going inside the if statement that checks to see if the closest
tr.child
is displayed and can't figure out why.

Answer

Change your js to following.

$(function () {
    $(".table tr:gt(0)").click(function (event) {
        $(this).next('tr.child').toggle();
    });
});

UPDATED FIDDLE

Comments