如何用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 || ' '}</td>`; cols += `<td>${email || ' '}</td>`; cols += `<td>${instagram || ' '}</td>`; cols += `<td>${celular || ' '}</td>`; cols += `<td>${facebook || ' '}</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> </td> <td> </td> <td> </td> <td> </td> <td> </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
相关产品推荐
相关产品推荐

