![](/img/trans.png)
[英]How to get multiple value of input field which is inside foreach loop using jquery?
[英]Pulling data from multiple input boxes in foreach loop using Jquery
我正在为项目创建订单。 我使用 Foreach 循环将数据从数据库中提取到我创建的表中。 但是当我将数量和单价数据相乘时,代码仅适用于表格第一行中的数据。 我如何修改所有传入循环数据的代码?
购物车 php:
<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>
Javascript 代码:
$(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);
});
});
});
打印:图片
如何编辑代码以在所有行上运行?
您已经为您的输入提供了class
,而不是id
。 这意味着您无法轻易区分它们。 然而,使用一些聪明的unitprice
代码,您可以识别数量发生变化的表格行,然后获取quantity
和单价并设置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)
,并两次获取父级:首先是<td></td>
,然后是<tr></tr>
。 我们将其存储在tableRow
中。 鉴于我们现在知道表行,我们可以使用find()访问输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.