Selecting ONLY the next <tr> inside dynamically generated table

Viewed 34

I'm generating a table via SQL/php. It outputs one .data-row and one .admin-row in each loop. When I click the edit icon <i class='edit-button'></i>, I only need it to open the next .admin-row right below the that the edit icon is in (screenshot).

Right now, I am using this jQuery code which opens all .admin-row class elements.

  $('.edit-button').click(function() {
    $('#dataTable').find('.admin-row').toggleClass('d-none');
  });

I've experimented with .next(), .parent(), .find() but can't get it to open only the next .admin-row after the edit button.

<?php
<table> ... / table head...

foreach($result as $row) {

echo "<tr class='data-row'>";
  echo "<td>".$date_form."</td>
  echo "<td>".$time_form."</td>
  echo "<td>".$subject_form."</td>
  echo "<td>".$public."</td>
if ($userUid == "admin") {
  echo "<td><i class='edit-button'></i></td>";
                   }
echo "</tr>";

if ($userUid == "admin") { ?>

<tr class='admin-row'>
  <form action="includes/update.inc.php" type="post">
    <td><input name="editId" type="text"></td>
    <td class='p-2' colspan="4">
      <textarea name="editContent" type="text"></textarea>
    </td>
    <td><button name="submit-edit" type="submit">EDIT</button></td>
  </form>
</tr>

 <?php }}?>
</table>

enter image description here

2 Answers

You can just use .closest() method for this like:

$('.edit-button').click(function() {
  $(this).closest('.data-row').next('.admin-row').toggleClass('d-none');
});

The issue was edit button is in another row and admin-row is a different row.

I also found in the demo, there is no class added like d-none. SO, I added one like:

.d-none {display: none}

Working Demo:

$('.edit-button').click(function() {
  $(this).closest('.data-row').next('.admin-row').toggleClass('d-none');
});
.d-none {display: none}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="1">
  <tr class="data-row">
    <td>Time/date</td>
    <td>Lorem Ipsum Lorem Ipsum Lorem Ipsum </td>
    <td><button class="edit-button" type="button">Edit
      </button>
    </td>
  </tr>
  <tr class="admin-row">
    <td>Data1</td>
    <td>Data2</td>
    <td>Data3</td>
  </tr>
  <tr class="data-row">
    <td>Time/date</td>
    <td>Lorem Ipsum Lorem Ipsum Lorem Ipsum </td>
    <td><button class="edit-button" type="button">Edit
      </button>
    </td>
  </tr>
  <tr class="admin-row">
    <td>Data1</td>
    <td>Data2</td>
    <td>Data3</td>
  </tr>
</table>

Please try something like this

$('.edit-button').click(function() {
  $(this).closest('.data-row').next().toggleClass('d-none');
});

First select the parent .data-row of button then toggle its next elements class.

Hope it helps!

Related