You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML动态生成字段总和计算失败问题求助

Fixing Dynamic Field Total Calculation

Hey there! Let's get that total sum working correctly for your dynamic fields. I've reviewed your code and found a couple of issues that are preventing the sum from calculating properly, plus some redundant code that's causing confusion. Here's the breakdown and fixed version:

Issues in Your Original Code

  • Duplicate remove event handlers: You've got two $(document).on('click', '.btn_remove', ...) blocks, which will fire twice when you delete a row and cause incorrect calculations.
  • Incorrect method for updating the label: You're using $("#total").val(sum) to update the <label> element, but labels don't have a value property—use .text() instead.
  • Broken delete calculation logic: The second remove handler references $(".total").val() which doesn't exist, leading to wrong total values when deleting rows.
  • Missing event binding for new fields: The initial keyup event only binds to the first .name_list input; dynamically added inputs won't trigger this event unless you use event delegation.

Fixed Complete Code

<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
    <form name="add_name" id="add_name">
        <div class="table-responsive">
            <table class="table table-bordered" id="dynamic_field">
                <tr>
                    <td><input type="text" name="name[]" placeholder="Enter a number" class="form-control name_list" /></td>
                    <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                </tr>
            </table>
            <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
        </div>
        <div>total <label id='total'>0</label></div>
    </form>

    <script>
        $(document).ready(function(){
            var i=1;

            // Add new dynamic row
            $('#add').click(function(){
                i++;
                $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter a number" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
                // Recalculate total after adding row (in case input has default value)
                calculateTotal();
            });

            // Remove row and recalculate total
            $(document).on('click', '.btn_remove', function(){
                var button_id = $(this).attr("id");
                $('#row'+button_id+'').remove();
                calculateTotal();
            });

            // Event delegation for keyup on ALL .name_list inputs (existing and new)
            $(document).on('keyup', '.name_list', function(){
                calculateTotal();
            });

            // Reusable function to calculate total
            function calculateTotal(){
                var sum = 0;
                $(".name_list").each(function(){
                    // Only add valid numbers, ignore empty or non-numeric values
                    var value = $(this).val().trim();
                    if(!isNaN(value) && value !== ''){
                        sum += Number(value);
                    }
                });
                $("#total").text(sum);
            }
        });
    </script>
</body>
</html>

Key Improvements

  • Single reusable calculation function: calculateTotal() handles all sum calculations, so we don't repeat code across add, remove, and keyup events.
  • Event delegation for dynamic inputs: Using $(document).on('keyup', '.name_list', ...) ensures every new input triggers the calculation.
  • Fixed label update: Uses .text(sum) to correctly set the label's content.
  • Error handling for invalid inputs: Checks if the input value is a valid number before adding it to the sum, so empty or non-numeric values don't break the total.
  • Removed duplicate event handlers: Only one remove event handler exists, which deletes the row and recalculates the total immediately.

内容的提问来源于stack exchange,提问作者Jasshh Andrews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:02:38