0

总和正确显示在所有浏览器中。现在,当我删除行时,总和的值会减少,但在 Firefox 浏览器中不能正确显示。假设 10 + 10 + 10 = 30 如果删除 2 行,则 sum 显示 20 。但这将是 10。出了什么问题。

<script>
    $(document).ready(function () {
        $("form").on('keyup', '.input_ttotal', function() {
            calculateSum();
        });

        $('#btnDel').click(function () {
            calculateSum();
        });

    });

    function calculateSum() {

        var sum = 0;

        $(".input_ttotal").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                sum += parseFloat(this.value);
            }
        });
        $("#sum").html(sum.toFixed(2));
    }
    </script>

html是

<form action="" method="POST">
    <div class="yes">
        <div id="cost1" class="clonedCost" style="display: inline;">
            <table border="0">
                <tr>
                    <td>
                        <label class="total" for="total">Total 1</label>
                    </td>
                </tr>
                <tr>
                    <input class="input_ttotal" id="ttotal" type="text" name="ttotal[]" />
                    </td>
                </tr>
            </table>
        </div>
        <div id="addDelButtons_cost">
            <input type="button" id="btnAdd" value="+">
            <input type="button" id="btnDel" value="-">
        </div>
        <p>Sum is:<span id="sum">0</span>
        </p>
    </div>
</form>

jsfiddle 链接是http://jsfiddle.net/ByLrz/1/

4

2 回答 2

0
$('#btnDel').click(function () {
        calculateSum();
    });

所有这一切都是调用 calculateSum 函数,该函数反过来计算".input_ttotal"输入中所有值的总和。

在任何时候都不会从表单中删除输入,因此总和将始终相同。

于 2013-08-01T14:21:44.747 回答
0

calculateSum();最有可能在元素被删除之前被调用。尝试将其添加到您的删除确认功能中http://gestionale.odoyabooks.com/scripts/other_book_cost.js

$('#btnDel').click(function () {

    if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
        {
            var num = $('.clonedCost').length;

            $('#cost' + num).slideUp('slow', function () {$(this).remove(); 

            // after $(this).remove() recalculate
            calculateSum();

                if (num -1 === 1)
            $('#btnDel').attr('disabled', true);

            $('#btnAdd').attr('disabled', false).prop('value', "");});
        }
    return false;

    $('#btnAdd').attr('disabled', false);
});
于 2013-08-01T14:47:35.810 回答