Gareth Gillman
Gareth Gillman

Reputation: 353

jQuery hide next element on change

I am trying to hide the next element with a class but I think it's getting confused by the html structure.

html:

<tr>
 <td>
  <input type="number" value="1" name="product_quantity" class="form-quantity" />
 </td>
 <td><a class="add_to_cart_button" href="#">Add To Cart</a></td>
</tr>

js:

$("tr").each(function() {
 $(this).find(".form-quantity").change(function() {
  $(this).closest(".add_to_cart_button").hide();
 });
});

JS Fiddle to see what I mean - https://jsfiddle.net/vpvw6t53/

I have tried using .parent, .children and .sibling so asking here :)

Upvotes: 1

Views: 737

Answers (2)

JJJ
JJJ

Reputation: 3332

Thanks to @barmar for pointing out that my solution wouldn't work in the context with the actual table. So I updated my answer.

$(document).ready(function() {
  $(".form-quantity").change(function() {
    $(this).parent().next().find(".add_to_cart_button").hide();
  });
});

Also, you don't need to loop over the tr elements so I removed that from the code.

$(document).ready(function() {
  $(".form-quantity").change(function() {
    $(this).parent().next().find(".add_to_cart_button").hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

  <tr>
    <td>
      <input type="number" value="1" name="product_quantity" class="form-quantity" />
    </td>
    <td><a class="add_to_cart_button" href="#">Add To Cart</a></td>
  </tr>
  <tr>
    <td>
      <input type="number" value="1" name="product_quantity" class="form-quantity" />
    </td>
    <td><a class="add_to_cart_button" href="#">Add To Cart</a></td>
  </tr>
</table>

Upvotes: 0

Guybrush
Guybrush

Reputation: 738

I cannot try it at this moment, but

$("tr").each(function() {
  $(this).find(".form-quantity").change(function() {
    $(this).closest("tr").find(".add_to_cart_button").hide();
 });
});

should work. Keep in mind that you select your Input element.

Upvotes: 1

Related Questions