提交表单后通过LocalStorage在另一页面展示多选框值
如何通过LocalStorage在页面间传递并展示复选框选中值?
没问题,我来帮你搞定这个需求。咱们分两个页面来实现,先处理提交页面的逻辑,把选中的复选框值存入LocalStorage;再做展示页面,读取并渲染这些值。
1. 提交页面(第一页)代码
首先给你的现有代码补充表单结构和JavaScript逻辑,这样就能在提交时收集选中的选项:
<!DOCTYPE html> <html> <head> <title>提交资质</title> </head> <body> <p id="qualifications">Qualifications:</p> <form id="qualificationForm"> <label for="checkbox1">BE</label> <input type="checkbox" value="BE" id="checkbox1" name="qualification"> <label for="checkbox2">MCA</label> <input type="checkbox" value="MCA" id="checkbox2" name="qualification"> <button type="submit">提交</button> </form> <script> // 获取表单元素 const form = document.getElementById('qualificationForm'); // 监听表单提交事件 form.addEventListener('submit', function(e) { // 阻止表单默认提交行为(避免页面刷新) e.preventDefault(); // 获取所有选中的复选框 const selectedCheckboxes = document.querySelectorAll('input[name="qualification"]:checked'); // 把选中的复选框值转成数组 const selectedValues = Array.from(selectedCheckboxes).map(checkbox => checkbox.value); // 将数组转成JSON字符串存入LocalStorage(因为LocalStorage只能存字符串) localStorage.setItem('selectedQualifications', JSON.stringify(selectedValues)); // 跳转到展示页面(这里假设第二页叫second-page.html,你可以改成自己的文件名) window.location.href = 'second-page.html'; }); </script> </body> </html>
关键逻辑说明:
- 给复选框统一加上
name="qualification",这样更容易批量获取选中项 - 用
querySelectorAll('input[name="qualification"]:checked')筛选出所有被选中的复选框 - 把选中值的数组转成JSON字符串存入LocalStorage,因为LocalStorage只支持存储字符串类型
- 提交后跳转到展示页面
2. 展示页面(第二页)代码
接下来写第二页的代码,负责读取LocalStorage里的值并展示:
<!DOCTYPE html> <html> <head> <title>展示选中资质</title> </head> <body> <h2>你选中的资质:</h2> <div id="qualificationDisplay"></div> <script> // 页面加载时读取LocalStorage window.addEventListener('load', function() { // 获取存储的选中值(记得转成数组) const selectedQualifications = JSON.parse(localStorage.getItem('selectedQualifications')) || []; const displayDiv = document.getElementById('qualificationDisplay'); // 判断是否有选中值 if (selectedQualifications.length > 0) { // 创建列表展示 const list = document.createElement('ul'); selectedQualifications.forEach(qual => { const listItem = document.createElement('li'); listItem.textContent = qual; list.appendChild(listItem); }); displayDiv.appendChild(list); } else { // 没有选中任何选项时的提示 displayDiv.textContent = '你没有选中任何资质'; } // 可选:读取后清除LocalStorage(避免下次打开页面还显示旧数据) localStorage.removeItem('selectedQualifications'); }); </script> </body> </html>
关键逻辑说明:
- 页面加载时从LocalStorage取出数据,用
JSON.parse转成数组,同时处理null的情况(比如用户直接打开第二页) - 根据数组长度判断是否有选中值,动态创建列表展示或者提示无选中项
- 可选:读取后清除LocalStorage,避免用户再次打开第二页时看到旧的选中数据
这样就能实现你想要的功能啦,两个页面配合起来,提交时存值,展示时取值渲染~
内容的提问来源于stack exchange,提问作者Nitin
相关产品推荐
相关产品推荐

