简体   繁体   中英

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

My code is: 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);
});

So currently I cant get the js to fire that gets the product of the two cells, qty and price. 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

Help appreciated as always.

You're only giving the elements a name attribute, but using the id selector ([id^=price]). It's much easier to give them a specific class than having to use that "id starts with" selector. 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:

$(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/

In your JS, you weren't using linetotal for the one dynamic input's 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> . 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. A new row is added. Say you made a typo so you go back and change it to "asd", then click somewhere. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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