jquery在动态表上将两个输入相加并在第三个中显示

时间:2013-03-27 20:20:26

标签: javascript jquery

使用SO社区,我有一个脚本,可以为表添加具有唯一名称的行。我想在每一行上取两个输入并将它们相乘并在第三个输入中显示结果。

小提琴在http://jsfiddle.net/yUfhL/231/

我的代码是: 的 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

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

所以目前我不能让js开火,获得两个单元格的数量,数量和价格。我想在linetotal中显示结果。

最后一部分是将所有细线总和显示为div grandtotal

中的总计

一如既往的帮助。

2 个答案:

答案 0 :(得分:3)

您只是为元素指定了name属性,但使用了id选择器([id ^ = price])。给它们一个特定的类要比使用“id starts with”选择器容易得多。此外,您何时需要计算行总数?你什么时候想要计算总计?什么事件?

以下是我对其外观的解释:

<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>

和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/

在您的JS中,您没有将linetotal用于一个动态输入name。我做了其他几个小修改。您也可以使用<thead><tbody><tfoot>,因为您在<table>中有这些部分。另外,我不认为在“产品”输入发生变化时自动添加新行是一个好设计。这可能经常发生,他们的意图可能不是添加新产品......按钮更友好。例如,假设您在第一个“产品”输入中键入“asdf”,然后单击某处。添加了一个新行。假设您输了一个拼写错误,然后返回并将其更改为“asd”,然后单击某处。添加了另一个新行。这似乎不对。

答案 1 :(得分:1)

这个功能可以解决问题:

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));

}

您只需将其绑定到表更改事件,以在每次输入更改时更新总计:

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

Here是一个工作小提琴。