首页  >  问答  >  正文

使用Jquery的foreach循环从多个输入框中提取数据

<p>我正在为一个项目创建一个订单。我使用 Foreach 循环将数据从数据库提取到我创建的表中。但是,当我将数量和单价数据相乘时,该代码仅适用于表第一行中的数据。如何针对所有传入循环数据修改此代码?</p> <p>购物车.php:</p> <pre class="brush:php;toolbar:false;"><form action="" method="POST"> <table class="table table-sm mb-3 text-center align-middle"> <thead> <tr> <th>Product Name</th> <th>Quantity</th> <th>Unit Price</th> <th>Total Price</th> </tr> </thead> <tbody> <?php foreach($ProductTbl as $productdata){ ?> <tr> <td><?= $productdata->productname ?></td> <td><input class="w-25 text-center quantity" type="text" name="quantity[]" value="0"></td> <td><input class="w-25 text-center unitprice" type="text" name="unitprice[]" value="<?= $productdata->unitprice ?>" disabled="disabled"></td> <td><input class="w-25 text-center totalprice" type="text" name="totalprice[]" value="" disabled="disabled"> €</td> </tr> <?php } ?> </tbody> </table></pre> <p>Javascript代码:</p> <pre class="brush:php;toolbar:false;">$(document).ready(function() { $('.quantity').keyup(function() { var quantity = $('.quantity').val(); var unitprice = $('.unitprice').val(); var totalprice = $('.totalprice').val(); var result = quantity * unitprice; $('.totalprice').val(result); }); }); });</pre> <p>打印: 图片</p> <p>如何编辑代码以在所有行上运行?</p>
P粉278379495P粉278379495385 天前463

全部回复(1)我来回复

  • P粉707235568

    P粉7072355682023-09-01 12:48:07

    您为输入指定了class,而不是id。这意味着您无法轻松地区分它们。但是,通过一些巧妙的 JQuery 代码,您可以识别数量发生更改的表行,然后获取 quantityunitprice 并设置 totalprice

    $(document).ready(function() {
        $('.quantity').keyup(function() {
            let tableRow = $(this).parent().parent();
            let quantity = tableRow.find('.quantity').val();
            let unitprice = tableRow.find('.unitprice').val(); 
            let totalprice = quantity * unitprice;
            tableRow.find('.totalprice').val(totalprice);
        })
    });
    

    因此,我们在这里获取数量输入 $(this),并获取父级两次:首先是 ,然后是 。我们将其存储在tableRow中。鉴于我们现在知道表行,我们可以使用 find() 访问输入.

    示例代码请参见:https://codepen.io/kikosoft/pen/oNMjqLd

    回复
    0
  • 取消回复