Afzal Khan
Afzal Khan

Reputation: 125

Multiplication of 2 columns in jQuery

I want the multiplication of 2 columns of each row. This is my code and also a script. This script is working but just for the first row the output of this script is:

enter image description here

The result of the 2nd row is wrong:

<form>
<table id="my-table">
  <?php
    $query3 = mysqli_query($con,"select * from orders") or die("sdfsfs");
    while($row3=mysqli_fetch_array($query3))
    {
        $quantity = $row3['quantity'];
        $unit_price = $row3['unit_price'];
        //$total = $quantity * $unit_price;
  ?>
        <tr>
           <td><input type="text" class="common quantity" name="1" id="quant" value="<?php echo $quantity; ?>"></td>
           <td><input type="text" class="common price" name="2" id="units" value="<?php echo $unit_price; ?>"></td>
           <td><input type="text" class="total" name="3" id="total" readonly></td>
       </tr>
 <?php } ?>
        <tr>
           <td colspan="2"><label class="form-control">Subtotal</label></td>
           <td><input name="subtotal" readonly id="subtotal" class="sub"  type="text" /></td>
        </tr>
</table>
</form>

jQuery

<script>
        $(".total").each(function() {
        $('.total').val(parseFloat($('#quant').val()) * parseFloat($('#units').val()));
        });
</script>

Upvotes: 1

Views: 1278

Answers (2)

Justinas
Justinas

Reputation: 43507

It's because you have same ID in every row, so your code always takes first occurrence of that ID - so always calculates only first row values. Replace ID's with classes

$(document).ready(function () {
  $('.quantity, .price').change(function () {
    var parent = $(this).closest('tr');
    parent.find('.total').val(parseFloat(parent.find('.quantity').val()) * parseFloat(parent.find('.price').val()))
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="text" class="common quantity quant" name="1">
    </td>
    <td>
      <input type="text" class="common price units" name="2">
    </td>
    <td>
      <input type="text" class="total" name="3" class="total" readonly>
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" class="common quantity quant" name="1">
    </td>
    <td>
      <input type="text" class="common price units" name="2">
    </td>
    <td>
      <input type="text" class="total" name="3" class="total" readonly>
    </td>
  </tr>
</table>

Upvotes: 2

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Iterate over the rows and use class instead of ID's otherwise it's only take the first matched only:

$("#my-table tr:not(:last)").each(function() {

    $(this).find('.total').val(parseFloat($(this).find('.quantity').val()) * parseFloat($(this).find('.price').val()));
    });

});

Upvotes: 4

Related Questions