1

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 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 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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

this code worked fine. thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.