bontoo bontoo - 3 months ago 30
HTML Question

jquery dropdown toggle table row

I am trying to create a dropdown toogle for a table. The main purpose is when a main row is clicked then its sub rows has to disappear.

The problem is when i insert a variable into the selector it is not working.

here is a similar table:

<table border="1">
<thead>
<tr class="btn-info">
<th>header</th>
<th>header</th>
</tr>
</thead>
<tr id="main1" class="bg-primary">
<td>maintext1</td>
<td>maintext1</td>
</tr>
<tr name="toggletext1" class="bg-info">
<td>subtext1</td>
<td>subtext1</td>
</tr>
<tr name="toggletext1" class="bg-info">
<td>subtext1</td>
<td>subtext1</td>
</tr>
<tr id="main2" class="bg-primary">
<td>maintext2</td>
<td>maintext2</td>
</tr>
<tr name="toggletext2" class="bg-info">
<td>subtext2</td>
<td>subtext2</td>
</tr>
<tr name="toggletext2" class="bg-info">
<td>subtext2</td>
<td>subtext2</td>
</tr>
</table>


and the script:

<script>
$(document).ready(function(){
for (x=1;x<=500;x++){
$('#main'+x).on('click', function() {
$("tr[name=toggletext"+x+"]").slideToggle();
});
}
});
</script>


if i change the script like:

$("tr[name=toggletext1]").slideToggle();


then it is working but obviously only the rows with the name of "toggletext1" will toggle. even if i click on the main with id=2;

any help would be appropriated

Answer

Try this ;)

$(document).ready(function() {
  $('.bg-primary').on('click', function() {
    $('.' + $(this).attr('id')).slideToggle();
  }).css('cursor', 'pointer');
});
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <thead>
    <tr class="btn-info">
      <th>header</th>
      <th>header</th>
    </tr>
  </thead>
  <tr id="main1" class="bg-primary">
    <td>maintext1</td>
    <td>maintext1</td>
  </tr>
  <tr class="bg-info main1 hide">
    <td>subtext1</td>
    <td>subtext1</td>
  </tr>
  <tr class="bg-info main1 hide">
    <td>subtext1</td>
    <td>subtext1</td>
  </tr>
  <tr id="main2" class="bg-primary">
    <td>maintext2</td>
    <td>maintext2</td>
  </tr>
  <tr name="toggletext2" class="bg-info main2 hide">
    <td>subtext2</td>
    <td>subtext2</td>
  </tr>
  <tr name="" class="bg-info main2 hide">
    <td>subtext2</td>
    <td>subtext2</td>
  </tr>
</table>