1

I would like to fetch items and item prices from database and use it to create an array of input fields for quantity and amount. Then use Jquery to automatically fetch the values of quantity as I type and multiply it by the price to display the amount in the amounts field for each item.

At the same time, the totals value (which is sum of all amounts) should also be displayed.

This is restricted to only the items that have been checked (selected).

<table class="form" id='tab1e'>
    <tr>
        <th>&nbsp;</th>
        <th style="text-align: left;">Material Name</th>
        <th style="text-align: center;">Quantity</th>
        <th style="text-align: center;">Unit Price</th>
        <th style="text-align: center;">Amount</th>
        <th style="text-align: center;">Currency</th>
    </tr>

    <?php
    foreach($database_result as $value){
    ?>

    <tr>
        <td>
            <input type="checkbox" name="checkboxes[]" value="<?php echo $row['price']."".$row['item_name'] ?>">
        </td>
        <td style="width: 150px">
        <?php echo $row['item_name'] ?>
        </td>
        <td>
            <input name="qnty[]" id="qnty">
        </td>
        <td>
            <input name="price" class="form-control" value="<?php echo $row['price']) ?>" id="price">
        </td>
        <td>
            <input name="total_amount[]" class="text form-control" readonly="readonly" id="total_amount">
        </td>
      </tr>
      <?php } ?>
      <tr>
        <td>Total Amount</td>
        <td style="text-align: right;" id="totalpop"></td>
        <td></td>
    </tr>
</table>

1 Answer 1

1

First thing is the inputs should have different ids. Now, you can use onchange event to call a function when input value changes. You can use plain javascript for that. Here's an example:

<html>
<body>

<script>
function o(id) {
  return document.getElementById(id);
}
function updatePrice(id) {
  if (!o('qnty'+id).value.match(/^[0-9]+$/)) {
    alert('Invalid quantity');
    o('total'+id).value = '0';
    return false;
  }

  // Similar check for price 
  o('total'+id).value = parseInt(o('qnty'+id).value) * parseFloat(o('price'+id).value);
}
</script>

<input name="qnty[]" onchange="updatePrice('1')" id="qnty1">
<input name="price" value="1" onchange="updatePrice('1')" id="price1">
<input name="total_amount[]" id="total1">

</body>
</html>

The 1 corresponds to row number, so you would need to change your PHP code so it has a row number (can be just a simple $i=1; before the loop and $i++; in the end of every loop iteration).

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

Comments

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.