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

动态添加行的HTML表单中jQuery自动填充功能失效求助

动态表单行自动填充失效的解决方案

问题核心

单行表单可正常从MySQL拉取数据自动填充,但通过JavaScript克隆新增行后,新行的自动填充功能完全失效——原因是原代码依赖固定ID定位输入框,克隆后ID重复冲突,且GetDetail函数仅操作初始行的固定ID元素。

修复方案(分步修改)

1. 重构HTML标记:移除固定ID,改用类名定位

原代码的id="aaa"/bbb/ccc会在克隆后重复,改用类名标识输入框,同时修改onkeyup事件传递当前元素而非仅值:

<td>
    <input type="text" class="form-control text-end scode" name="scode[]"                    
           onkeyup="GetDetail(this)" value="">
</td>
<td>
    <input type="text" class="form-control text-end servproname" 
           name="servproname[]">
</td>
<td>
    <input type="text" class="form-control text-end qty" name="qty[]">
</td>

2. 修改GetDetail函数:动态定位当前行的输入框

让函数接收当前输入元素,通过DOM关系找到所在行的目标输入框,避免依赖固定ID:

function GetDetail(inputElement) {
    const str = inputElement.value;
    // 定位当前输入框所在的表格行
    const currentRow = inputElement.closest('tr');
    // 找到当前行内的目标输入框
    const servpronameInput = currentRow.querySelector('.servproname');
    const qtyInput = currentRow.querySelector('.qty');

    if (str.length === 0) {
        servpronameInput.value = "";
        qtyInput.value = "";
        return;
    }

    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            const myObj = JSON.parse(this.responseText);
            servpronameInput.value = myObj[0] || "";
            qtyInput.value = myObj[1] || "";
        }
    };

    // 对请求参数编码,避免URL格式问题
    xmlhttp.open("GET", "gfg.php?user_id=" + encodeURIComponent(str), true);
    xmlhttp.send();
}

3. 优化PHP脚本:修复SQL注入漏洞

原代码直接拼接SQL参数存在注入风险,改用预处理语句优化:

<?php
// 获取请求参数,默认空值避免报错
$user_id = $_REQUEST['user_id'] ?? '';

// 数据库连接
$con = mysqli_connect("localhost", "root", "", "hmis");

$bbb = '';
$ccc = '';

if (!empty($user_id)) {
    // 预处理语句防止SQL注入
    $stmt = mysqli_prepare($con, "SELECT name, qty1 FROM machine1 WHERE user_id = ?");
    mysqli_stmt_bind_param($stmt, "s", $user_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_array($result);
    
    if ($row) {
        $bbb = $row["name"];
        $ccc = $row["qty1"];
    }
}

// 返回JSON格式结果
$result = array($bbb, $ccc);
echo json_encode($result);
?>

4. 动态添加行代码(无需核心修改,保留原逻辑)

克隆行的代码可继续使用,因为已改用类名定位,不会再出现ID冲突:

function BtnAdd() {
    const newRow = $("#TRow").clone().appendTo("#TBody");
    newRow.find("input").val('');
    newRow.removeClass("d-none");
    newRow.find("th").first().html($('#TBody tr').length - 1);
}

关键修改说明

  • 用类名替代固定ID:解决克隆后ID重复导致的元素定位混乱
  • 基于DOM关系动态定位:通过closest('tr')锁定当前行,确保填充操作只作用于触发事件的行
  • 安全优化:PHP预处理语句防范SQL注入,前端参数编码避免URL解析错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:47:46