简体   繁体   中英

jquery find closest class and increase value

I have buttons to increase/decrease quantity in a cart

<div class="product-quantity">
  <button class="qtyminus">-</button>
  <input type="text" name="quantity" value="1" class="qty form-control">
  <button class="qtyplus">+</button>
</div>

my javascript unfortunately doesn't work can't figure out why.

$('.qtyplus').on('click', function(e) {
    e.preventDefault();
    var num = Number($(this).closest('.qty').val());
    $(this).closest('.qty').val(++num);
});

jQuery closest searches ancestors, but in this case, you're looking for the sibling element. Try siblings instead of closest

By the way, modern browsers have built-in debugging tools. It's easy to set a breakpoint and step through you code to see what's happening, and to use the console window to test things.

You should use siblings() instead of closest() as closest() searches for ancestors while siblings() searches for siblings of an element.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="product-quantity"> <button class="qtyminus">-</button> <input type="text" name="quantity" value="1" class="qty form-control"> <button class="qtyplus">+</button> </div> <script> $('.qtyplus').on('click', function(e) { e.preventDefault(); var num = Number($(this).siblings('.qty').val()); $(this).siblings('.qty').val(++num); }); $('.qtyminus').on('click', function(e) { e.preventDefault(); var num = Number($(this).siblings('.qty').val()); $(this).siblings('.qty').val(--num); }); </script> 

Your issue is because closest() looks up the DOM, yet .qty is a sibling to the clicked buttons, so you need to use siblings() instead.

Also note that you can use a single event handler for both buttons if you put a common class on them and provide the value to add in a data attribute. You can also negate the need to repeatedly select the same element by providing a function to val() which returns the new value based on its current one. Try this:

 $('.amendqty').on('click', function(e) { e.preventDefault(); var inc = $(this).data('inc'); $(this).siblings('.qty').val(function(i, v) { return parseInt(v, 10) + inc; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="product-quantity"> <button class="amendqty" data-inc="-1">-</button> <input type="text" name="quantity" value="1" class="qty form-control"> <button class="amendqty" data-inc="1">+</button> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM