Nguyen Hoang
Nguyen Hoang

Reputation: 548

Get value from an input when click button in foreach

@foreach ($products as $product)
<h3>{{ $product->name }}</h3>
<input type="number" class="quantity" />
<button id="btn-buy" class="select-buy">Buy</button>
@endforeach

I want to get value of in quantity input field when I click on the Buy button. The problem is I can get the value but I don't know how to get it into an foreach loop. Please help. Thanks.

Upvotes: 0

Views: 1153

Answers (2)

cezar62882
cezar62882

Reputation: 69

You can use closest function and then find the text field.

php code

@foreach ($products as $product) 
<h3>{{ $product->name }}</h3> 
<div class="row"> 
    <input type="number" class="quantity" /> 
    <button id="btn-buy" class="select-buy">Buy</button> 
</div> 
@endforeach

javascript code

<script>
$(".select-buy").on('click', function(){
  var val = $this.closest('div').find('.quantity').val();

  alert(val);
});
</script>

Upvotes: 1

Pars
Pars

Reputation: 5272

You can use prev() function in jquery

I think this should work

$(function(){
    $(document).on('click', '.select-buy', function() {
        // get previous element value only if it is an input
        var value = $( this ).prev().val();
    });
});

Upvotes: 0

Related Questions