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

如何用jQuery将表单数据添加至表格?含按钮布局问题

解决方案:通讯录表单数据录入与按钮静态布局修复

问题1:将表单数据填充到表格行中

当前的AddTableRow()函数仅添加空行,需修改它来获取表单输入值并插入到新行内:

修改后的functions.js代码:

(function($) {
  window.AddTableRow = function() {
    // 获取表单各字段值
    const nome = $('input[name="nome"]').val().trim();
    const email = $('input[name="email"]').val().trim();
    const celular = $('input[name="cel"]').val().trim();
    const instagram = $('input[name="insta"]').val().trim();
    const facebook = $('input[name="face"]').val().trim();

    // 基础验证:姓名为必填项
    if (!nome) {
      alert('Por favor, preencha o nome');
      return false;
    }

    // 构建带数据的新行
    const newRow = $("<tr>");
    let cols = "";
    cols += `<td>${nome || '&nbsp;'}</td>`;
    cols += `<td>${email || '&nbsp;'}</td>`;
    cols += `<td>${instagram || '&nbsp;'}</td>`;
    cols += `<td>${celular || '&nbsp;'}</td>`;
    cols += `<td>${facebook || '&nbsp;'}</td>`;
    cols += `<td><button type="button" onclick="remove(this)" class="btn btn-danger btn-xs">Excluir</button></td>`;

    newRow.append(cols);
    $("#myTable tbody").append(newRow); // 插入到tbody中,保证表格结构合规

    // 清空表单,优化操作流程
    $('#formulario')[0].reset();

    return false;
  };
})(jQuery);

(function($) {
  window.remove = function(item) {
    const tr = $(item).closest('tr');
    tr.fadeOut(400, function() {
      tr.remove();  
    });
    return false;
  }
})(jQuery);

核心改动说明:

  • 通过$('input[name="字段名"]')精准获取每个输入框的内容
  • 增加基础必填项验证,避免空数据提交
  • 将新行插入到表格的<tbody>标签内,修复原代码破坏表格结构的问题
  • 添加数据后自动清空表单,提升用户操作体验

问题2:固定“Salvar”按钮实现静态布局

原代码将按钮放在表格<tfoot>的<tr>内,不符合HTML规范(<tr>仅允许嵌套<td>),需调整结构并利用Bootstrap类实现固定:

修改后的HTML表格区域代码:

<!-- 顶部固定的Salvar按钮 -->
<div class="container mt-3 sticky-top bg-white pb-2">
  <button class='btn btn-danger' onclick="AddTableRow()" type="button">Salvar</button>
</div>

<!-- 数据表格 -->
<div class="container mt-3">
  <table class="table table-striped" id="myTable">
    <thead>
      <tr>
        <th>Nome</th>
        <th>Email</th>
        <th>Instagram</th>
        <th>Celular</th>
        <th>Facebook</th>
        <th>Excluir</th>
      </tr>
    </thead>
    <tbody>
      <!-- 初始空行(可根据需求删除) -->
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>
          <button type="button" onclick="remove(this)" class="btn btn-danger btn-xs">Excluir</button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

核心改动说明:

  • 将按钮移出表格,放入独立容器,使用sticky-top类实现页面滚动时按钮固定在顶部
  • 修正表格结构:将表头从<tbody>移至<thead>标签内,符合HTML表格标准
  • 若需固定在表格底部,可将按钮容器放在表格之后,替换为sticky-bottom类(需注意避免被页脚遮挡,可调整容器margin-bottom值)

内容的提问来源于stack exchange,提问作者JOÃO AUGUSTO VENANCIO DA SILVA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:11:31