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

动态表格行数据存储:每行3个输入值存入子数组(JavaScript)

问题需求与现有代码

我有一个动态表格,添加行时希望保存输入框中的数据。目前能将所有数据存入一个一维数组,但需求是每行的3个输入值对应一个子数组,形成二维数组。作为JavaScript新手,实现过程中遇到了困难,现有代码如下:

现有JavaScript代码

function arraySaveData() {

    var data = [];

    for (var index = 0; index < 1; index++) {

        $('#mytableform1').each(function (_, element) {

            var element = document.getElementsByName("namesavedata[]");

            for (var i = 0; i < element.length; i++) {

                data.push(element[i].value);
            }

        });

        
        var result = [];

        for(var i = 0; i < data.length; i++) {

            var obj = {}

            obj= data[i];

            result.push(obj)

        }
        console.log(result)

    }

}


//Button add table row 
function addRow() {

    var table = document.getElementById("mytableform1");
    var rowCount = table.rows.length;

    x = document.getElementById("mytableform1").rows.length;

    var row = table.insertRow();
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    //numeração crescente
    for (var i = 0; i < x; i++) {

        cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="' +
            (cell1.innerHTML = i + 0) +
            '">';

        cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';

        cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';

    }
}
//Button delete table row 
function deleteRow() {
    var table = document.getElementById("mytableform1");
    var rowCount = table.rows.length;

    if (rowCount >= 4) {
        table.deleteRow(rowCount - 1);
    } else {
        Swal.fire({
            title: 'Erro!',
            text: "Não pode apagar este campo",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e55353',
            cancelButtonColor: '#636f83',
            confirmButtonText: 'ok'
        })
    }

}

现有HTML代码

<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
   <tr>
      <td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
      <td colspan="3" align="center" valign="top">Coordenadas no sistema PT -  TM06/ETRS89</td>
   </tr>
   <tr>
      <td align="center" valign="top">M(m)</td>
      <td align="center" valign="top">P(m)</td>
   </tr>
   <tr name="allDataRow">
      <td align="center" valign="top">
         <input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_1" placeholder="1">
      </td>
      <td align="center" valign="top">
         <input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_2" placeholder="00000,000">
      </td>
      <td align="center" valign="top">
         <input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_3" placeholder="00000,000">
      </td>
   </tr>
</table>
<div style="display:flex;justify-content: space-between;">
   <div style="display:flex;">
      <button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
      <span class="bi bi-plus-square-dotted"></span>+
      </button>
      <button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
      <span class="bi bi-plus-square-dotted"></span>-
      </button>
   </div>
   <div style="display:flex;">
      <button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
      Validar dados da tabela
      </button>
   </div>
</div>
解决方案

问题分析

  1. arraySaveData函数逻辑冗余:仅将所有输入值推入一维数组,未按行分组;多余循环无实际作用。
  2. addRow函数存在错误循环:会重复覆盖单元格内容,导致输入框生成异常。

修正后的代码

JavaScript部分

function arraySaveData() {
    const result = [];
    // 筛选表格中所有数据行(跳过前两行表头)
    const dataRows = document.querySelectorAll('#mytableform1 tr[name="allDataRow"]');
    
    dataRows.forEach(row => {
        // 获取当前行的三个输入框
        const inputs = row.querySelectorAll('input[name="namesavedata[]"]');
        if (inputs.length === 3) {
            // 将当前行的三个值组成子数组,推入结果数组
            const rowData = [
                inputs[0].value.trim(),
                inputs[1].value.trim(),
                inputs[2].value.trim()
            ];
            result.push(rowData);
        }
    });
    
    console.log('二维数组数据:', result);
}

// 修正添加行函数
function addRow() {
    const table = document.getElementById("mytableform1");
    // 计算新行的序号(前两行是表头,数据行数量=总行数-2)
    const newRowIndex = table.rows.length - 1;

    const row = table.insertRow();
    // 标记为数据行,方便后续筛选
    row.setAttribute('name', 'allDataRow');
    const cell1 = row.insertCell(0);
    const cell2 = row.insertCell(1);
    const cell3 = row.insertCell(2);

    // 生成当前行的三个输入框,序号自动递增
    cell1.innerHTML = `<input type="number" class="form-control" name="namesavedata[]" align="center" placeholder="${newRowIndex}">`;
    cell2.innerHTML = '<input type="number" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
    cell3.innerHTML = '<input type="number" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
}

// 优化删除行逻辑
function deleteRow() {
    const table = document.getElementById("mytableform1");
    const rowCount = table.rows.length;

    // 保留至少1行数据(总行数>3时可删除,前两行是表头)
    if (rowCount > 3) {
        table.deleteRow(rowCount - 1);
    } else {
        Swal.fire({
            title: 'Erro!',
            text: "Não pode apagar este campo",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e55353',
            cancelButtonColor: '#636f83',
            confirmButtonText: 'ok'
        })
    }
}

关键改进点

  • arraySaveData函数:直接遍历数据行,每行生成一个包含3个输入值的子数组,最终形成二维数组,逻辑清晰高效。
  • addRow函数:移除错误循环,直接生成一行的三个输入框;给新行添加name="allDataRow"标记,方便后续精准筛选数据行;自动计算行序号,无需手动维护。
  • deleteRow函数:调整判断逻辑为总行数>3时允许删除,确保至少保留1行数据,逻辑更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:21:24