Richard Brensom Richard Brensom - 1 month ago 11
Javascript Question

Accordion table showing another table

I am trying to set an accordion in multiple tables.
Once user clicks on a

<tr>
, another table shows at the bottom.

HTML



<table class="table m-0 stocks" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr class="parent-clickable">
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td>+</td>
</tr>
<tr class="hidden">
<td colspan="5">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
<td>+</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>


JS



$(document).ready(function() {
$("parent-clickable").click(function() {
var text = $(this).closest("tr").find(".hidden").slideToggle(200, "linear");
});
console.log("Clicked");
});


JSFIDDLE

Answer

Some little things to fix in your code, HTML is fine.

$(document).ready(function() {
  $(".parent-clickable").click(function() {
    $(this).next(".hidden").slideToggle(200, "linear");
    console.log("Clicked");
  });

});

You forgot to add the selector in front of "parent-clickable" in this case, a class so prefix it with a dot.

using .closest and .find seems redudant in this case, when a single .next can help achieve what you want. Finally, if you are not using it elsewhere, there's no need to store all this in a variable.