HTML内嵌JS无法为动态表格行添加data-form-field属性致表单提交异常
直接修正方案
针对动态行无法被表单采集的问题,核心修改点完全匹配现有表单的收集规则,不需要调整原有邮件提交逻辑:
- 核心适配规则:表单只识别带
data-form-field属性的输入元素,因此动态生成的三个文本输入框,必须和静态行使用完全相同的属性值,不能使用泛化的字段名 - 现有逻辑bug1:原
addRow函数生成的输入元素没有设置data-form-field属性,直接导致新增行内容被表单采集逻辑跳过 - 现有逻辑bug2:原
deleteRow函数通过childNodes[0]查找checkbox的方式稳定性差,遇到带空白文本节点的单元格会定位错误元素,甚至触发空节点报错 - 现有逻辑bug3:原动态行的输入框命名使用无区分的
txtbox[],后端无法区分不同列的字段含义,容易出现内容错位
修正后可直接复用的完整脚本
function addRow(tableID) { const table = document.getElementById(tableID); const rowTotal = table.rows.length; const newRow = table.insertRow(rowTotal); // 第一列:选择删除的checkbox const cellCheck = newRow.insertCell(0); cellCheck.style.textAlign = "center"; const checkInput = document.createElement("input"); checkInput.type = "checkbox"; checkInput.name = `select_row[${newRow.rowIndex}]`; cellCheck.appendChild(checkInput); // 第二列:Part序号 const cellPart = newRow.insertCell(1); cellPart.style.textAlign = "center"; cellPart.textContent = newRow.rowIndex; // 第三列:Marca输入框 const cellMarca = newRow.insertCell(2); cellMarca.style.textAlign = "center"; const marcaInput = document.createElement("input"); marcaInput.type = "text"; marcaInput.size = "10"; marcaInput.style.textAlign = "center"; // 对齐静态行的字段采集标识 marcaInput.setAttribute("data-form-field", "Marca"); cellMarca.appendChild(marcaInput); // 第四列:Referencia输入框 const cellRef = newRow.insertCell(3); cellRef.style.textAlign = "center"; const refInput = document.createElement("input"); refInput.type = "text"; refInput.size = "7"; refInput.style.textAlign = "center"; refInput.setAttribute("data-form-field", "Ref"); cellRef.appendChild(refInput); // 第五列:Producto输入框 const cellProd = newRow.insertCell(4); cellProd.style.textAlign = "center"; const prodInput = document.createElement("input"); prodInput.type = "text"; prodInput.size = "35"; prodInput.style.textAlign = "center"; prodInput.setAttribute("data-form-field", "Prod"); cellProd.appendChild(prodInput); } function deleteRow(tableID) { try { const table = document.getElementById(tableID); const rowTotal = table.rows.length; // 从第1行开始遍历,跳过无checkbox的表头行 for (let i = 1; i < rowTotal; i++) { const currentRow = table.rows[i]; // 用选择器精确定位checkbox,避免文本节点干扰 const rowCheck = currentRow.cells[0].querySelector('input[type="checkbox"]'); if (rowCheck && rowCheck.checked) { table.deleteRow(i); rowTotal--; i--; } } } catch (e) { alert(e); } }
效果验证
替换原有脚本后:
- 动态新增的所有行输入框,都会被表单的采集逻辑识别,填写的内容会和静态行内容一同打包进邮件发送
- 删除操作不会触发定位错误的报错,勾选行后即可正常删除
- 行号会自动随行的位置连续生成,不会出现序号错位
注意:不需要修改原有静态表格的结构,直接替换JS代码即可,所有属性值和静态行的匹配规则完全对齐,不会和现有表单提交逻辑产生冲突。
内容的提问来源于stack exchange,提问作者Santiago España
相关产品推荐
相关产品推荐

