I am creating an order form for a project. I pulled data from the database with the Foreach loop to the table I created. But when I multiply the quantity and unit price data, the code works only for the data in the first row of the table. How can I revise this code for all incoming loop data?
Cart.php:
<form action="" method="POST">
<table >
<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 type="text" name="quantity[]" value="0"></td>
<td><input type="text" name="unitprice[]" value="<?= $productdata->unitprice ?>" disabled="disabled"></td>
<td><input type="text" name="totalprice[]" value="" disabled="disabled"> €</td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript code:
$(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);
});
});
});
Print: Image
How do I edit the code to run on all lines?
CodePudding user response:
You've given your inputs a class
, not an id
. This means you cannot easily distinguish between them. However, with a bit of clever JQuery code you can identify the table row in which the quantity was changed, and then get the quantity
and unitprice
and set the 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);
})
});
So here we take the quantity input, $(this)
, and get the parent twice: First the <td></td>
and then the <tr></tr>
. We store this in tableRow
. Given that we now know the table row, we can get access to the inputs by using find().
For example code see: https://codepen.io/kikosoft/pen/oNMjqLd