0

我有一个表,最后有复选框列。

HTML

<table border="1">
    <thead>
        <tr>
            <td>Name</td>
            <td>Amount</td>
            <td>Selected Rows</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Item 1</td>
            <td>5.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
        <tr>
            <td>Item 2</td>
            <td>3.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
        <tr>
            <td>Item 3</td>
            <td>4.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
    </tbody>
</table>
Total : $<input type="text" value="12.0" />

jQuery

$('input[type=checkbox]').change(function(){
   alert($(this).parent().parent().text());
});

我想根据使用复选框选择的行计算总值。该代码$(this).parent().parent().text();给出了整行的文本值。如何单独获取金额列的值?

JSFIDDLE

4

1 回答 1

2

您需要遍历行并汇总检查的值。试试这个:

$('input[type=checkbox]').change(function () {
    var total = 0;
    $('table tbody tr').each(function () {
        if ($('input:checked', this).length) {
            total += parseFloat($(this).find('td:eq(1)').text());
        }
    });
    $('#total').val(total.toFixed(1));
});

示例小提琴

可以通过添加一些类或 id 属性来改进 DOM 遍历以使其更具体到表/输入,但用于计算总数的模式在任何情况下都可以工作。

于 2013-02-05T11:09:28.657 回答