I want to get input field values which are in foreach loop using jquery . Here is the html structure
@foreach ($products as $product) <div class = "form-row"> <input type="text" name="quantity" class="form-control quantity"value="{{$product->quantity }}"> <input type="text" name="price" class="form-control price"value="{{$product->price}}"> </div> @endforeach
I’m trying to get value in this way
var quantity = $('.quantity').val(); var price= $('.price').val();
But In this way, I get only first-row value. How can get all rows value using jquery?
Advertisement
Answer
You have to loop through all the elements to get the values from them.
You can try jQuery’s .map()
and .get()
to get all the values in an array.
Demo:
var quantityArr = $('.quantity').map(function(){ return +this.value; }).get(); console.log(quantityArr); // if you want the value comma separated then join the array var quantityCommaSeperatedString = quantityArr.join(','); console.log(quantityCommaSeperatedString); var priceArr = $('.price').map(function(){ return +this.value; }).get(); console.log(priceArr); // if you want the value comma separated then join the array var priceCommaSeperatedString = priceArr.join(','); console.log(priceCommaSeperatedString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="quantity" class="form-control quantity"value="1"> <input type="text" name="price" class="form-control price"value="10"> <input type="text" name="quantity" class="form-control quantity"value="2"> <input type="text" name="price" class="form-control price"value="20"> <input type="text" name="quantity" class="form-control quantity"value="3"> <input type="text" name="price" class="form-control price"value="30">
Update: As mentioned in the comment: get values by row
$('.form-row').click(function(){ var quantity = $(this).find('.quantity').val(); console.log(quantity); var price = $(this).find('.price').val(); console.log(price); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class = "form-row"> <input type="text" name="quantity" class="form-control quantity"value="1"> <input type="text" name="price" class="form-control price"value="10"> </div> <div class = "form-row"> <input type="text" name="quantity" class="form-control quantity"value="2"> <input type="text" name="price" class="form-control price"value="20"> </div> <div class = "form-row"> <input type="text" name="quantity" class="form-control quantity"value="3"> <input type="text" name="price" class="form-control price"value="30"> </div>