簡體   English   中英

如何從 jquery 的輸入字段中獲取多個值?

[英]How to get multiple values from input field in jquery?

我想使用 jquery 獲取 foreach 循環中的輸入字段值。 這里是html結構

    @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

我試圖以這種方式獲得價值

     var quantity = $('.quantity').val();
     var price= $('.price').val();

但這樣,我只得到第一行的價值。 如何使用 jquery 獲取所有行值?

您必須遍歷所有元素才能從中獲取值。

您可以嘗試使用 jQuery 的.map().get()來獲取數組中的所有值。

演示:

 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">

更新:如評論中所述:按行獲取值

 $('.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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM