如何将表单值动态添加到HTML表格的新行中?
动态将表单值添加到HTML表格的解决方案
需求:每次提交表单时,将表单中的值作为新行追加到HTML表格中,确保多次提交能依次添加新行。
现有HTML表单结构
<form id="schedule-form"> <label for="Name">Name:</label> <input type="text" name="Name" id="name"> <label for="program">Course:</label> <select id="program"> <option value="BSIT">BSIT</option> <option value="BSHM">BSHM</option> <option value="BSCRIM">BSCRIM</option> <option value="BSED">BSED</option> <option value="BEED">BEED</option> </select> <label for="subjects">Subject:</label> <select id="subjects"></select> <label for="room">Room:</label> <select id="room"> <option value="IT Room 1">IT Room 1</option> <option value="IT Lab 1">IT Lab 1</option> <option value="IT Lab 2">IT Lab 2</option> <option value="IT Lab 3">IT Lab 3</option> </select> <label for="day">Day:</label> <select id="day"> <option value="MWF">MWF</option> <option value="TTH">TTH</option> <option value="Mon">Mon</option> <option value="Tue">Tue</option> <option value="Wed">Wed</option> <option value="Thu">Thu</option> <option value="Fri">Fri</option> </select> <label for="start-time">Start Time:</label> <input type="time" id="start-time"> <label for="end-time">End Time:</label> <input type="time" id="end-time"> <button type="submit">Schedule</button> </form>
课程表格结构
<h3>Scheduled Classes</h3> <table> <thead> <th>Name</th> <th>Course</th> <th>Subject</th> <th>Room</th> <th>Day</th> <th>Time</th> </thead> <tbody id="schedule-table"> </tbody> </table>
修正后的JavaScript代码
你可以通过以下步骤实现动态添加行的功能:
- 获取表格的
<tbody>元素,作为追加新行的目标容器 - 创建新的
<tr>元素作为表格行 - 为每个表单值创建对应的
<td>单元格并填充内容 - 将所有单元格添加到新行,再把新行追加到
<tbody>中 - 可选:提交后重置表单,方便用户输入下一条数据
完整代码如下:
document.getElementById('schedule-form').addEventListener('submit', function(e) { e.preventDefault(); // 获取表单值 let name = document.querySelector('[name="Name"]').value; let course = document.getElementById('program').value; let subject = document.getElementById('subjects').value; let room = document.getElementById('room').value; let day = document.getElementById('day').value; let startTime = document.getElementById('start-time').value; let endTime = document.getElementById('end-time').value; // 获取表格tbody元素 const tableBody = document.getElementById('schedule-table'); // 创建新行 const newRow = document.createElement('tr'); // 创建单元格并填充内容 const cells = [ name, course, subject, room, day, `${startTime} - ${endTime}` // 合并开始和结束时间 ]; cells.forEach(cellText => { const cell = document.createElement('td'); cell.textContent = cellText; newRow.appendChild(cell); }); // 将新行添加到表格 tableBody.appendChild(newRow); // 重置表单(可选) this.reset(); });
关键说明
document.createElement():每次提交生成全新的表格行和单元格DOM节点,避免重复元素问题appendChild():将单元格依次添加到行内,再把整行追加到表格主体,实现持续添加新行的效果- 表单重置:调用
this.reset()清空表单输入框,提升用户操作体验 - 时间合并:把开始和结束时间合并为一个单元格内容,匹配表格的"Time"列展示需求
内容的提问来源于stack exchange,提问作者AYBAN
相关产品推荐
相关产品推荐

