How can I change nearest input with jQuery?

I'm editing woocomerce plugin. I want to create quantity button that will change nearest product quantities when click.

<div class='product-1'>
    <div class='changeQtyButton'>
         <button class='buttonNumber'>1</button>
         <button class='buttonNumber'>2</button>
         <button class='buttonNumber'>3</button>
    <div>
    <div class='quantity'>
         <input class='quantityInput-1'>
    <div>
</div>
<div class='product-2'>
    <div class='changeQtyButton'>
         <button class='buttonNumber'>1</button>
         <button class='buttonNumber'>2</button>
         <button class='buttonNumber'>3</button>
    <div>
    <div class='quantity'>
         <input class='quantityInput-2'>
    <div>
</div>

<script>
    jQuery('button').on('click', function(){
       //inputQty = jQuery(this).next('input').attr('name') ;
        test = jQuery(this).closest( "div.changeQtyButton" ).find("input[name=''quantity]").val();
       console.log(test);
    });
 </script>

So how can I select the nearest input when click the button?

Upvotes: 0

Views: 52

Answers (1)

pavel
pavel

Reputation: 27082

You need to go one level up, find next element and input inside.

$('button').on('click', function() {
    $(this).parent().next().find('input')
})

.parent() is .changeQtyButton
.next() is .quantity

Or

$(this).closest('[class^=product-]').find('input')

Upvotes: 2

Related Questions