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

Bootstrap模态框传值至克隆输入框异常:所有行同步更新相同数据

问题解决:Bootstrap模态框填充动态表单行时所有行同步更新的问题

问题原因

  1. 重复绑定事件:每次按下Enter键打开模态框时,都会为模态框的选择按钮新增一个click事件监听。多次操作后,点击选择按钮会触发所有已绑定的事件,导致所有之前触发过的行都被填充数据。
  2. 重复ID属性:模态框内所有选择按钮都使用了id="selected",HTML规范中ID必须唯一,这会导致元素选择和事件绑定出现冲突。

修复代码

1. 修正JavaScript逻辑

$(document).ready(function() {
    // 实时搜索逻辑
    $(".card").on('keyup', '.live_search', function() {
        var input = $(this).val();
        if (input != "") {
            $.ajax({
                type: "POST",
                url: "livesearch.php",
                data: {
                    input: input
                },
                success: function(data) {
                    $(".searchresult").html(data);
                    $(".searchresult").css("display", "block");
                }
            });
        } else {
            $(".searchresult").css("display", "none");
        }
    });

    // 添加行逻辑
    $(".add-row").click(function(e) {
        e.preventDefault();
        $("#show-item").prepend(`<tr>
                        <input type="hidden" name="id[]">
                        <td class="col-2">
                            <div class="input-group input-group-sm">
                                <a href="#" class="btn btn-danger delete-row"> <i class="fa-solid fa-trash-can"></i>
                                </a>
                                <input type="text" class="form-control live_search" name="material_name[]" placeholder="Nombre Material">
                            </div>
                        </td>
                        <td class="col-1">
                            <div class="input-group  input-group-sm ">
                                <input type="text" class="form-control" name="measure_one[]">
                            </div>
                        </td>
                        <td class=" col-1">
                            <div class="input-group  input-group-sm ">
                                <input type="text" class="form-control" name="measure_two[]">
                            </div>
                        </td>
                        <td class=" col-2">
                            <div class="input-group  input-group-sm ">
                                <input type="text" class="form-control" name="unit_measure[]">
                            </div>
                        </td>
                        <td class=" col-1">
                            <div class="input-group  input-group-sm ">
                                <input type="text" class="form-control" name="length[]">
                            </div>
                        </td>
                        <td class=" col-1">
                            <div class="input-group  input-group-sm ">
                                <input type="text" class="form-control" name="width[]">
                            </div>
                        </td>
                        <td class=" col-1">
                            <div class="input-group  input-group-sm">
                                <input type="text" class="form-control" name="price[]">
                            </div>
                        </td>
                    </tr>`);
    });

    // 删除行逻辑
    $('.card').on('click', '.delete-row', function(evt) {
        evt.preventDefault();
        $(this).closest('tr').remove();
    });

    // 存储当前激活的表单行
    let currentActiveRow = null;

    // 打开模态框逻辑
    $('.card').on('keyup', '.live_search', function(e) {
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if (keycode == '13') {
            // 记录当前触发的行
            currentActiveRow = $(this).closest('tr');
            $('#insert').modal({
                backdrop: 'static',
                keyboard: false
            }).modal('show');
            return false;
        }
    });

    // 委托模态框内的选择按钮点击事件(仅绑定一次)
    $('#insert').on('click', '.selected', function(e) {
        e.preventDefault();
        if (!currentActiveRow) return;

        var id = $(this).data('material-id');
        var material = $(this).data('material-name');
        var measure_one = $(this).data('material-measure_one');
        var measure_two = $(this).data('material-measure_two');
        var unit_measure = $(this).data('material-unit_measure');
        var length = $(this).data('material-length');
        var width = $(this).data('material-width');
        var price = $(this).data('material-price');

        // 仅填充当前激活的行
        currentActiveRow.find('[name="id[]"]').val(id);
        currentActiveRow.find('[name="material_name[]"]').val(material);
        currentActiveRow.find('[name="measure_one[]"]').val(measure_one);
        currentActiveRow.find('[name="measure_two[]"]').val(measure_two);
        currentActiveRow.find('[name="unit_measure[]"]').val(unit_measure);
        currentActiveRow.find('[name="length[]"]').val(length);
        currentActiveRow.find('[name="width[]"]').val(width);
        currentActiveRow.find('[name="price[]"]').val(price);

        $('#insert').modal('hide');
        // 重置当前激活行
        currentActiveRow = null;
    });
});

2. 修正PHP生成的模态框表格代码

if (mysqli_num_rows($result) > 0) { ?>
    <table class="table table-bordered table-striped table-hover table-sm text-center">
        <thead class="table-primary">
            <tr>
                <th>ID</th>
                <th>Proveedor</th>
                <th>Material</th>
                <th>Acciones</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = mysqli_fetch_assoc($result)) :
                $id = $row['supplier_id'];
                $supplier = $row['supplier'];
                $material = $row['material'];
            ?>
                <tr>
                    <td><?php echo $id ?></td>
                    <td><?php echo $supplier ?></td>
                    <td><?php echo $material ?></td>
                    <td>
                        <?php echo '<a href="#" class="btn btn-link selected" data-material-id="' . $row['supplier_id'] . '"
                         data-material-name="' . $row['material'] . '" data-material-measure_one="' . $row['measure_one'] . '"
                          data-material-measure_two="' . $row['measure_two'] . '" data-material-unit_measure="' . $row['unit_measure'] . '" 
                          data-material-length="' . $row['length'] . '" data-material-width="' . $row['width'] . '" 
                          data-material-price="' . $row['price']  . '">Select</a>';
                        ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
<?php } ?>

关键修复点说明

  • 新增currentActiveRow变量存储当前触发模态框的表单行,避免事件重复绑定导致的多更新问题。
  • 将模态框的选择按钮事件改为委托绑定,仅绑定一次,避免重复绑定。
  • 将选择按钮的id="selected"改为class="selected",符合HTML唯一ID规范。
  • 使用data()方法替代attr()获取data属性,更符合jQuery的最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:54:24