简体   繁体   English

jQuery求和动态表上的两个输入并显示在第三

[英]jquery to sum two inputs on dynamic table and display in third

With the SO community I have got a script that adds rows with unique names to a table. 在SO社区中,我有一个脚本,可将具有唯一名称的行添加到表中。 I want to take two inputs on each row and multiply them together and display result in a third input. 我想在每行上输入两个输入并将它们相乘,然后在第三个输入中显示结果。

the fiddle is at http://jsfiddle.net/yUfhL/231/ 小提琴在http://jsfiddle.net/yUfhL/231/

My code is: HTML 我的代码是: HTML

<table class="order-list">
  <tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
  <tr>
      <td><input type="text" name="product" /></td>
      <td><input type="text" name="price" /></td>
      <td><input type="text" name="qty" /></td>
      <td><input type="text" name="linetotal" /></td>
    </tr>
</table>
<div id="grandtotal">
    Grand Total Here
</div>

JS JS

var counter = 1;
jQuery("table.order-list").on('change','input[name^="product"]',function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('<tr><td><input type="text" name="product' +
        counter + '"/></td><td><input type="text" name="price' +
        counter + '"/></td><td><input type="text" name="qty' +
        counter + '"/></td><td><input type="text" name="total' +
        counter + '"/></td><td><a class="deleteRow"> x </a></td></tr>');
    jQuery('table.order-list').append(newRow);
});

jQuery("table.order-list").on('click','.deleteRow',function(event){

    $(this).closest('tr').remove();
});

$('table.order-list tr').each(function() {
   var price = parseInt( $('input[id^=price]', this).val(), 10 );
   var qty   = parseInt( $('input[id^=qty]'  , this).val(), 10 );
   $('input[id^=linetotal]', this).val(price * qty);
});

So currently I cant get the js to fire that gets the product of the two cells, qty and price. 所以目前我无法启动js来获取两个单元格(数量和价格)的乘积。 I want to display result in linetotal. 我想以合计显示结果。

The last part of this would be to display the sum of all linetotals as a grand total in the div grandtotal 最后一部分将显示所有linetotal的总和,作为div grandtotal中的grandtotal

Help appreciated as always. 帮助一如既往地受到赞赏。

You're only giving the elements a name attribute, but using the id selector ([id^=price]). 您只给元素一个name属性,而是使用id选择器([id ^ = price])。 It's much easier to give them a specific class than having to use that "id starts with" selector. 给他们一个特定的类比必须使用“ id开头”选择器要容易得多。 Also, when do you want the line totals to be calculated? 另外,什么时候要计算行总数? And when do you want the grand total to be calculated? 而您希望什么时候计算总计呢? On what event(s)? 在什么事件上?

Here's my interpretation of how it should look: 这是我对外观的解释:

<table class="order-list">
    <thead>
        <tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
    </thead>

    <tbody>
        <tr>
            <td><input type="text" name="product" /></td>
            <td>$<input type="text" name="price" /></td>
            <td><input type="text" name="qty" /></td>
            <td>$<input type="text" name="linetotal" readonly="readonly" /></td>
            <td><a class="deleteRow"> x </a></td>
        </tr>
    </tbody>

    <tfoot>
        <tr>
            <td colspan="5" style="text-align: center;">
                <input type="button" id="addrow" value="Add Product" />
            </td>
        </tr>

        <tr>
            <td colspan="5">
                Grand Total: $<span id="grandtotal"></span>
            </td>
        </tr>
    </tfoot>
</table>

And the JS: 和JS:

$(document).ready(function () {
    var counter = 1;

    $("#addrow").on("click", function () {
        counter++;

        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="text" name="product' + counter + '"/></td>';
        cols += '<td>$<input type="text" name="price' + counter + '"/></td>';
        cols += '<td><input type="text" name="qty' + counter + '"/></td>';
        cols += '<td>$<input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
        cols += '<td><a class="deleteRow"> x </a></td>';
        newRow.append(cols);

        $("table.order-list").append(newRow);
    });

    $("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
        calculateRow($(this).closest("tr"));
        calculateGrandTotal();
    });

    $("table.order-list").on("click", "a.deleteRow", function (event) {
        $(this).closest("tr").remove();
        calculateGrandTotal();
    });
});

function calculateRow(row) {
    var price = +row.find('input[name^="price"]').val();
    var qty = +row.find('input[name^="qty"]').val();
    row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}

function calculateGrandTotal() {
    var grandTotal = 0;
    $("table.order-list").find('input[name^="linetotal"]').each(function () {
        grandTotal += +$(this).val();
    });
    $("#grandtotal").text(grandTotal.toFixed(2));
}

http://jsfiddle.net/QAa35/ http://jsfiddle.net/QAa35/

In your JS, you weren't using linetotal for the one dynamic input's name . 在您的JS中,您没有将linetotal用作一个动态输入的name There were other several minor modifications I made. 我还有其他一些小的修改。 You might as well use <thead> , <tbody> and <tfoot> since you do have those sections in the <table> . 您最好使用<thead><tbody><tfoot>因为您确实在<table>有这些部分。 Also, I don't think it's a good design to have a new row automatically added when the "product" inputs are changed. 另外,我认为更改“产品”输入时自动添加新行并不是一个好的设计。 That can happen often, and their intent may not be to add a new product...a button is much more friendly. 这种情况经常发生,他们的意图可能不是添加新产品……按钮更加友好。 For example, say you type in "asdf" to the first "product" input, then click somewhere. 例如,假设您在第一个“产品”输入中键入“ asdf”,然后单击某个位置。 A new row is added. 添加新行。 Say you made a typo so you go back and change it to "asd", then click somewhere. 假设您输入了错误,然后返回并将其更改为“ asd”,然后单击某个位置。 Another new row is added. 添加另一行。 That doesn't seem right. 那似乎不对。

This function should do the trick: 这个函数应该可以解决问题:

function updateGrandTotal() {

    var prices = [];
    $('input[name^="price"]').each(function () {
        prices.push($(this).val());
    });

    var qnts = [];
    $('input[name^="qty"]').each(function () {
        qnts.push($(this).val());
    });

    var total = 0;
    for(var i = 0; i < prices.length; i++){
        total += prices[i] * qnts[i];
    }

    $('#grandtotal').text(total.toFixed(2));

}

You just need to bind it to the table change event to update the grand total every time an input changes: 您只需要将其绑定到表更改事件即可在每次输入更改时更新总计:

$("table.order-list").change(updateGrandTotal);

Here is a working fiddle. 是一个工作的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM