计算数量乘以单位价格输入和相等输入将是小计并且总和所有小计

I need to calculate quantity multiply unit price inputs and equal input will be subtotal and sum all subtotals...

I used this code in javascript, and it is working fine, but in table didn't work.

Please help.

HTML/PHP:

<table border="0" cellspacing="0" class="table table-bordered table-hover" data-name="cont-table">
    <thead style="">
        <tr>
            <th class="check-this"><input class="check_all" type="checkbox" onclick="select_all()"/></th>
            <th class="text-center"> م </th>
            <th class="text-center"> اسم الصنف </th>
            <th class="text-center"> الوحدة </th>
            <th class="text-center"> الكمية </th>
            <th class="text-center"> سعر الوحدة </th>
            <th class="text-center"> العام المالي </th>
            <th class="text-center"> إجمالي قيمة الصنف </th>
        </tr>
    </thead>
    <tr>
        <td><input type="checkbox" class="case"/></td>
        <td><span id="snum">1.</span></td>
        <td><!--<input type="text" id="first_name" name="first_name[]"/>!-->
        <select class="select" id="first_name" name="first_name[]">
            <?php
                $stmt = $db->query("SELECT first_name6 FROM item");
                //$stmt = $pdo->execute();
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    echo "<option >" . $row['first_name6'] . "</option>";
                }
            ?>
        </select></td>
        <td><!--<input type="text" id="last_name" name="last_name[]"/>!-->
        <select class="select" id="first_name" name="first_name[]">
            <?php
                $stmt = $db->query("SELECT first_name7 FROM unit");
                //$stmt = $pdo->execute();
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    echo "<option >" . $row['first_name7'] . "</option>";
                }
            ?>
        </select></td>
        <td><input class="select qty" type="number" id="tamil" name="tamil[]"/></td>
        <td><input class="select unit" type="number" id="english" name="english[]" /></td>
        <td><!--<input type="text" id="computer" name="computer[]"/>!-->
        <select class="select " id="first_name" name="first_name[]">
            <?php
                $stmt = $db->query("SELECT first_name8 FROM financial");
                //$stmt = $pdo->execute();
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    echo "<option >" . $row['first_name8'] . "</option>";
                }
            ?>
        </select></td>
        <td><input type="text" id="total" class="amount" value="" /></td>
    </tr>
</table>
<button id="add_row"  type="button" class="delete btn btn-default pull-right">مسح</button>
<button id="add_row" style="margin-right:5px;" type="button" class="addmore btn btn-default pull-right">اضاف صنف</button>
<br>
<br>
<h3 class="table-h3 " style="text-align:center;">اجمالي قيمة العقد</h3>
<input type="text" name="totalprice" class="result" value="" />

and this is the javascript code:

$(".qty").on('input', function () {
    var self = $(this);
    var unitVal = self.next().val();
    self.next().next().val(unitVal * self.val());
    fnAlltotal();
});
$(".unit").on('input', function () {
    var self = $(this);
    var qtyVal = self.prev().val();
    self.next().val(qtyVal * self.val());
    fnAlltotal();
});
function fnAlltotal(){
    var total=0
    $(".amount").each(function(){
        total += parseFloat($(this).val()||0);
    });
    $(".result").val(total);
}

Your JavaScript code is not attaching event handlers to any of the input elements that do not exist yet, but only to the single pair of text inputs that exists at page load.

When you add rows, the input event on those new input elements will not be captured. To achieve that, you should use event delegation.

Secondly, your input elements are all single children of their parent td elements, so when you apply the next method on them, it will not return anything.

Instead, you could retrieve the table row the event is being triggered on and then read the values from both the .unit and .qty inputs in that row to then update the .amount element in that same row:

// Use event delegation to capture events on rows that will only exist in future
$(document).on('input', '.qty, .unit', function (e) { // get event
    // get number of row this event is occurring in:
    var row = $(e.target).closest('tr').index();
    // get both unit and qty from that row:
    var unitVal = $('.unit').eq(row).val(); 
    var qtyVal = $('.qty').eq(row).val(); 
    // update the amount in that row:
    $('.amount').eq(row).val(unitVal * qtyVal);
    // adapt total (no change to your code)
    fnAlltotal();
});

As you can see in the code below, the input has no next:

<td><input class="select qty" type="number" id="tamil" name="tamil[]"/></td>

It is alone in the td element.

See next() in jQUery documentation, it says:

.next()

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

And as I said earlier, the input element in question has no siblings, it is alone...

So, when you run...

self.next()

It selects nothing, and thus...

self.next().val()

Returns undefined.

A similar problem exists on the code using prev.


It at all possible access these fields by id, if you need to have multiple instances of these fields in the page, I would suggest to generate ids form them with PHP.


Working example using classes (the HTML is made of fragments of the OP):

$(".qty").on('input', compute);
$(".unit").on('input', compute);
function compute()
{
  // // if there is only one element with those classes
  // var qtyVal = $(".qty").val();
  // var unitVal = $(".unit").val();
  // // otherwise...
  
  // get the tr that contains the element that triggered the event
  var tr = $(this).closest("tr");
  var qtyVal = tr.find(".qty").val(); // find .qty within that tr
  var unitVal = tr.find(".unit").val(); // find .unit within that tr
  
  // check for when the input aren't found
  if (typeof qtyVal == "undefined" || typeof unitVal == "undefined")
  {
    // leave the function
    return;
  }
  
  // write amount

  // // if there is only one element with those classes
  // $(".amount").val(qtyVal * unitVal);
  // // otherwise...

  tr.find(".amount").val(qtyVal * unitVal);

  // call fnAlltotal
  fnAlltotal();
}
function fnAlltotal(){
    var total=0
    $(".amount").each(function(){
        total += parseFloat($(this).val()||0);
    });
    $(".result").val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table><tr>
    <td><input class="select qty" type="number" id="tamil" name="tamil[]"/></td>
    <td><input class="select unit" type="number" id="english" name="english[]" /></td>
    <td><!--<input type="text" id="computer" name="computer[]"/>!-->
    <select class="select " id="first_name" name="first_name[]">
        <!-- PHP generated code -->
    </select></td>
    <td><input type="text" id="total" class="amount" value="" /></td>
</tr></table>
<!-- later -->
<input type="text" name="totalprice" class="result" value="" />

</div>