每行实时计算

时间:2013-05-03 18:41:27

标签: jquery html-table jquery-calculation

我有一个桌子里面有几个单元格,其中一个是数量,另一个是单位价格现在我在计算每一行的小计(模糊)时遇到问题。我不知道我是否正走在正确的轨道上。

<div class="widget-body" style="padding: 10px 0 0;">
    <table class="table table-primary table-bordered" id="tableaux">
        <thead>
            <tr>
                <th>Repair Type</th>
                <th>Detail Part Name</th>
                <th>Quantity</th>
                <th>Unit Price</th>
                <th>Subtotal</th>
                <th>Remove</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <select style="width: auto;" id="repairtype_id1" name="repairtype_id1" class="repairtype">
                        <option value="1">Single</option>
                        <option value="2">Parts</option>
                        <option value="3">Enhancement</option>
                    </select>
                </td>
                <td><input type="text" name="part_name1" id="part_name1" class="part_name" /></td>
                <td><input type="text" name="qty1" id="qty1" style="width: 50px;" class="qty" /></td>
                <td><input type="text" name="unit_price1" id="unit_price1" style="width: 100px;" class="price" /></td>
                <td class="subtotal"><input type="text" class="subtot" id="subtot1" style="width: 100px;" /></td>
                <td>&nbsp;&nbsp;&nbsp;&#x2716;</td>
            </tr>       
        </tbody>
    </table>
</div> <?php echo br()?>

    <button type="submit" class="btn btn-icon btn-primary glyphicons circle_ok" id="saveRepair"><i></i>Record Repair</button>
</form>

    <button class="btn btn-icon btn-primary glyphicons magic" id="addAnother"><i></i>Add Another Item</button>

function addTableRow(table)
    {
        var $tr = $(table).find("tbody tr:last").clone();
        $tr.find("input,select").attr("name", function(){
            var parts = this.id.match(/(\D+)(\d+)$/);

            return parts[1] + ++parts[2];
        }).attr("id", function(){
            var parts = this.id.match(/(\D+)(\d+)$/);
            return parts[1] + ++parts[2];
    });
    $(table).find("tbody tr:last").after($tr);
  };

$('#addAnother').on( 'click', function () {
        addTableRow($("table"));

        return false;
    });

$('table').live('input.subtot', 'blur', function(){
            var row = $(this).closest('tr');
            $(this).val(
                    $('.qty', row).val()*
                    $('.price', row).val()
            );
        });

这是当前的小提琴。

http://jsfiddle.net/XC3w4/

1 个答案:

答案 0 :(得分:1)

以下是您要找的内容:

$(document).on("change", ".price", function() {
    var units = this.value;
    var quantity = $(this).parent().prev().children("input").val();
    var subtotal = Number(units) * Number(quantity);

    $(this).parent().next().children("input").val(subtotal);
});

这是更新的小提琴:http://jsfiddle.net/XC3w4/1/

注意:您必须更改addNewRow方法,因为它克隆了前一行,包括输入中的值!

相关问题