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

JavaScript动态添加行中Select联动填充TextBox问题求助

问题分析与解决方案

问题核心在于动态生成的DOM元素未绑定事件——页面加载时绑定的change事件仅对初始存在的select框生效,后续新增的元素不会自动继承事件绑定;另外如果用全局选择器填充输入框,也无法精准定位到当前行的对应控件。

解决步骤:

  1. 改用事件委托绑定change事件
    将事件绑定到页面加载时就存在的静态父容器(比如表格的<tbody>),而非直接绑定到select元素。这样动态生成的select触发change时,事件会冒泡到父容器被捕获。

  2. 精准定位当前行的输入框
    在事件处理函数中,通过当前触发事件的select元素找到它所在的行,再在该行内查找对应的unit_price输入框,避免误操作其他行的控件。

示例代码:

前端JavaScript修改:

// 假设表格tbody的id为materials-tbody
$('#materials-tbody').on('change', '.material-select', function() {
    const materialId = $(this).val();
    const $currentRow = $(this).closest('tr'); // 获取当前操作的行

    if (materialId) {
        $.ajax({
            url: 'get_material_info.php', // 后端接口地址
            type: 'POST',
            data: { material_id: materialId },
            dataType: 'json',
            success: function(res) {
                // 填充当前行的unit_price输入框,假设输入框类名为unit-price-input
                $currentRow.find('.unit-price-input').val(res.unit_price);
                // 其他需要填充的字段(如规格、库存等)同理处理
            },
            error: function() {
                alert('获取原材料信息失败');
            }
        });
    } else {
        // 清空当前行的输入框
        $currentRow.find('.unit-price-input').val('');
    }
});

动态生成行的代码规范:

新增行时要给select框和输入框加上统一类名,确保事件委托和元素查找能匹配到:

function addNewMaterialRow() {
    const newRow = `
        <tr>
            <td>
                <select class="material-select" name="material_id[]">
                    <!-- 动态渲染或静态添加原材料选项 -->
                </select>
            </td>
            <td><input type="text" class="unit-price-input" name="unit_price[]" readonly></td>
        </tr>
    `;
    $('#materials-tbody').append(newRow);
}

后端PHP接口(get_material_info.php)示例:

<?php
// 数据库连接(根据实际配置修改)
$conn = mysqli_connect('localhost', 'db_user', 'db_pwd', 'db_name');

$materialId = $_POST['material_id'];
// 预处理SQL避免注入
$query = "SELECT unit_price FROM raw_materials WHERE id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 'i', $materialId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$materialData = mysqli_fetch_assoc($result);

// 返回JSON格式数据
echo json_encode([
    'unit_price' => $materialData['unit_price'] ?? ''
]);

mysqli_close($conn);
?>

关键注意点:

  • 事件委托必须绑定到静态存在的父元素,不能绑定到动态生成的元素本身;
  • 用closest()方法精准定位当前行,避免全局选择器导致的错误填充;
  • 动态生成的元素要保留统一类名,确保事件和选择器能正确匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:48:32