Extract data from multiple input boxes using Jquery's foreach loop
P粉278379495
2023-08-31 19:09:32
<p>I am creating an order for a project. I'm using a Foreach loop to pull data from the database into a table I've created. However, when I multiply the quantity and unit price data, the code only works for the data in the first row of the table. How can I modify this code for all incoming loop data? </p>
<p>Shopping cart.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 code: </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>Print:
Picture</p>
<p>How can I edit the code to run on all lines? </p>
You specified
class
for the input, notid
. This means you can't easily tell them apart. However, with some clever JQuery code you can identify the table row where the quantity changed, then get thequantity
andunitprice
and set thetotalprice 代码>:
So here we get the quantity input
$(this)
, and get the parent twice: first
, then
. We store it intableRow
. Given that we now know the table rows, we can use find() to access the input.For sample code, please see: https://codepen.io/kikosoft/pen/oNMjqLd一个>