How to get input value when I have multiple tags with same class name? For example, I have multiple product in my cart. And each product have different id
& prod_id
. My problem is whenever I try to get the value from the input field, it always return the first data even though I clicked on the latest.
Here is my blade view:
<div class="number-input mb-4">
<input id="qty" class="quantity" min="1" name="quantity" value="{{ $cart->quantity }}" type="number" readonly />
<input type="hidden" class="id" name="id" value="{{ $cart->id }}">
<input type="hidden" class="prod_id" name="prod_id" value="{{ $cart->product_id }}">
<button type="button" class="plus"></button>
</div>
And this is my jquery code:
$(".plus").click(function(e) {
let id = $(".id").val();
let product_id = $(".prod_id").val();
console.log(id);
console.log(product_id);
...
Thanks
CodePudding user response:
With .closest()
you can look for parents with a selector, then you van find the inputs inside that parent:
let container = $(this).closest('.number-input');
let id = container.find(".id").val();
let product_id = container.find(".prod_id").val();
Kinda hard to explain, but this way you stay within the same item.