Extract data from multiple input boxes using Jquery's foreach loop
P粉278379495
P粉278379495 2023-08-31 19:09:32
0
1
474
<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>
P粉278379495
P粉278379495

reply all(1)
P粉707235568

You specified class for the input, not id. 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 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 get the quantity input $(this), and get the parent twice: first , then . We store it in tableRow. 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一个>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!