Home  >  Q&A  >  body text

Extract data from multiple input boxes using Jquery's foreach loop

<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粉278379495P粉278379495436 days ago495

reply all(1)I'll reply

  • P粉707235568

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

    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

    reply
    0
  • Cancelreply