vrwd vrwd - 2 months ago 5
jQuery Question

How to use jQuery's "closest" function with multiple toggles of same classes / id's?

Have tried a few different methods with no success, so am reaching out on here in hope someone can assist, I have scaled back the code below to it's most basic (and unfunctional form), basically what I need is I will have heaps of table rows the same way as shown below, but I want each checkbox action to trigger the toggle of the closest set of items.

Code is below:



$(document).ready(function() {

$("input#change").change(function() {
$("span.disabled").toggle();
$("span.enabled").toggle();
$("span.pending").toggle();
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form action="page.php" method="post">

<table>
<!-- Row 1 -->
<tr>
<td>
<span class="pending" style="display:none;">PENDING</span>
<span class="disabled">DISABLED</span>
</td>
<td>
<input type="checkbox" name="statusArray[]" id="change" value="1" />
</td>
</tr>
<!-- Row 2 -->
<tr>
<td>
<span class="pending" style="display:none;">PENDING</span>
<span class="enabled">ENABLED</span>
</td>
<td>
<input type="checkbox" name="statusArray[]" id="change" value="2" />
</td>
</tr>
</table>

</form>





The top code works if there is one row only, but I need it to handle multiple rows.

The checkbox will always be named
statusArray[]
and tagged as
#change


There are 3 spans, though each row will only have two at any one time, these will be
span.enabled
,
span.disabled
and
span.pending


Is there a way using jquery to activate the
toggle
only on the current table row? I need to figure out something that would achieve this.

Any assistance is much appreciated.

Answer

Try this- made #change to class as multiple id are not possible.

Using closest('tr') to solve the issue- snippet below. Let me know your feedback on this. Thanks!

$(document).ready(function() {

  $("input.change").change(function() {
    $this = $(this).closest('tr');   
    
    $this.find("span.disabled").toggle();
    $this.find("span.enabled").toggle();
    $this.find("span.pending").toggle();
  });

});
<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<body>
  <form action="page.php" method="post">
    <table>
      <!-- Row 1 -->
      <tr>
        <td>
          <span class="pending" style="display:none;">PENDING</span>
          <span class="disabled">DISABLED</span>
        </td>
        <td>
          <input type="checkbox" name="statusArray[]" class="change" value="1" />
        </td>
      </tr>
      <!-- Row 2 -->
      <tr>
        <td>
          <span class="pending" style="display:none;">PENDING</span>
          <span class="enabled">ENABLED</span>
        </td>
        <td>
          <input type="checkbox" name="statusArray[]" class="change" value="2" />
        </td>
      </tr>
    </table>

  </form>


</body>

</html>

Comments