【问题标题】:calculate quantity multiply unit price input and equal input will be subtotal and sum all subtotals计算数量乘以单价输入和相等的输入将是小计并将所有小计相加
【发布时间】:2016-10-16 02:48:53
【问题描述】:

我需要计算数量乘以单价输入,相等的输入将是小计并将所有小计相加......

我在 javascript 中使用了这段代码,它工作正常,但在表中没有工作。

请帮忙。

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="" />

这是javascript代码:

$(".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);
}

【问题讨论】:

    标签: javascript php jquery


    【解决方案1】:

    您的 JavaScript 代码没有将事件处理程序附加到任何尚不存在的 input 元素,而只是附加到页面加载时存在的一对文本 inputs。

    当您添加行时,这些新 input 元素上的 input 事件将不会被捕获。为此,您应该使用event delegation

    其次,您的 input 元素都是其父 td 元素的单个子元素,因此当您对它们应用 next 方法时,它不会返回任何内容。

    相反,您可以检索触发事件的表行,然后从该行中的.unit.qty 输入中读取值,然后更新同一行中的.amount 元素:

    // 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();
    });
    

    【讨论】:

    • 是的,当我在表格中添加行时,这段代码确实比上面的代码更有帮助,非常感谢..
    • 你好,检查后我在表列中的每一行中都有删除行,如果我删除行,则未计算的结果仍然是相同的数字。我需要在删除行时更新结果输入..请帮忙
    • 当用户点击“删除”按钮时,只需调用fnTotal
    • 对不起,如何使它成为删除代码: $(".delete").on('click', function() { $('.case:checkbox:checked').parents ("tr").remove(); $('.check_all').prop("checked", false); check(); });
    • 这真的是一个不同的问题。请把它作为一个新问题发布。如果您愿意,您可以在此处发布指向该新问题的链接,然后我会查看它。
    【解决方案2】:

    正如您在下面的代码中看到的,input 没有next

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

    它单独存在于td 元素中。

    next() in jQUery documentation,上面写着:

    .next()

    获取匹配元素集中每个元素的紧随其后的兄弟。如果提供了选择器,则仅当它与该选择器匹配时才会检索下一个兄弟。

    正如我之前所说,所讨论的input 元素没有兄弟姐妹,它是单独的......

    所以,当你跑步时……

    self.next()
    

    它什么都不选择,因此...

    self.next().val()
    

    返回undefined

    使用prev的代码也存在类似问题。


    id 完全可以访问这些字段,如果您需要在页面中有这些字段的多个实例,我建议使用 PHP 生成它们的 id。


    使用类的工作示例(HTML 由 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="" />

    【讨论】:

    • 感谢您提供有用的答案,但我在搜索功能时使用类输入,因为当我在表中添加 raw 时 id 它发生了变化。这个带有添加、删除行的表编辑器......我们可以用使用类?
    • @PeterAzer 该类是否始终只有一个元素?如果是这样,那么是的,您可以使用类来做到这一点,只是要明确。也就是说,直接选择元素,而不是使用prevnext。否则,您将需要使用parentchildren 在DOM 树上上下移动。使用closest 编辑trincot suggest 也可能有效。
    • 对不起,我开始 javascript 你可以给我写代码吗?
    猜你喜欢
    • 2016-12-08
    • 2016-03-15
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多