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

使用jQuery添加表格行后PHP表单提交仅能获取首行数据如何解决

问题原因1:表单标签嵌套位置错误

你当前把<form>标签放在了<tbody>内部,不符合HTML规范,浏览器会自动修正错位的DOM结构,导致后续通过JS追加到<table>里的行不在表单范围内,提交时自然不会携带这些动态行的输入数据。

修正方案:把<form>标签移到<table>外层,包裹整个表格、添加/删除按钮和提交按钮:

<form action="index.php" method="post">
  <input type="button" class="btn btn-dark" id="addrow" value="Add Row">
  <table id="partstable" style="padding:15px;margin:15px;">
    <thead>
      <tr>
        <th></th>
        <th></th>
        <th>Qty</th>
        <th>Length</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox" name="record[]" style="margin:0 10px 0 -15px"></td>
        <td><input class="form-control" type="number" name="partid[]"></td>
        <td><input class="form-control" type="number" min="1" step="1" name="partqty[]" placeholder="Qty"></td>
        <td><input class="form-control" type="number" min="0.0001" step="0.0001" name="partlength[]" placeholder="Length"></td>
      </tr>
    </tbody>
  </table>
  <button type="button" class="btn btn-dark delete-row">Delete Row</button>
  <input name="submit" class="btn btn-success" type="submit" value="Submit">
</form>

问题原因2:新增行逻辑的计数变量位置错误

你把计数变量i放在了click事件内部,每次点击添加行都会把i重置为1,虽然不影响name数组的提交,但会导致所有动态行的ID重复,同时你现有代码里length输入框的ID和qty输入框ID重复,属于冗余问题。

修正方案:把i移到事件外部定义,同时修正重复ID的问题:

// 把i放在事件外部做全局计数
let i = 1;
$("#addrow").click(function(){
    var row = '<tr>'
    + '<td><input type="checkbox" name="record[]" style="margin:0 10px 0 -15px"></td>'
    + '<td><input class="form-control" type="number" name="partid[]" id="pid'+i+'"></td>'
    + '<td><input class="form-control" type="number" min="1" step="1" name="partqty[]" id="pqty'+i+'" placeholder="Qty"></td>'
    // 修正length的ID避免重复
    + '<td><input class="form-control" type="number" min="0.0001" step="0.0001" name="partlength[]" id="plength'+i+'" placeholder="Length"></td>'
    + '</tr>';
    i++;
    $("#partstable tbody").append(row);
});

问题原因3:PHP遍历逻辑写法错误

你现有foreach循环里直接把整个数组赋值给变量,写法冗余,按索引对应取值即可:

<?php
if(isset($_POST['submit'])){
    // 按行遍历,三个数组长度一致,用索引对应取值
    foreach($_POST['partid'] as $key => $partid){
       $partqty = $_POST['partqty'][$key];
       $partlength = $_POST['partlength'][$key];
       // 此处可替换为你的业务处理逻辑
       echo "第".($key+1)."行数据:零件ID=$partid,数量=$partqty,长度=$partlength <br>";
    }
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:45:09