将表单序列化到本地存储/在页面重新加载后恢复它(没有 jQuery)

Serialize a form to localStorage / restore it after page reload (without jQuery)

我有一个 <form> 有几个单选按钮组:

<form>
Group 1: 
<input type='radio' name='a' value='1'>
<input type='radio' name='a' value='2'>
<input type='radio' name='a' value='3'><br>
Group 2: 
<input type='radio' name='b' value='1'>
<input type='radio' name='b' value='2'>
<input type='radio' name='b' value='3'>
</form>

如何在每次选择更改事件时将所有内容保存到 localStorage,然后在页面重新加载时(例如,在我们关闭并重新打开浏览器后)重新加载之前选择的项目?

我对此的所有想法似乎都不必要地复杂。

我们可能必须为事件 "radio button is selected" 分配一个侦听器,或者我们应该简单地使用 "change" 事件来检测吗?

注意:这解决了 <input type="text"> 的类似问题:

也许有更简单的方法:

我们能否将一个整个<form>状态(输入值、选中的单选按钮等)序列化为localStorage,以及轻松恢复它,无需 jQuery?(无需为文本输入编写特定代码、为单选按钮编写其他代码、为复选框编写其他代码等)

  1. 创建一个辅助函数来检索表单值:

  2. 添加事件侦听器以形成更改:

  3. 内部事件侦听器将表单数据保存到 localStorage:

  4. 创建 "onload" 事件并从 localStorage 填充表单值: and https://benalexkeen.com/autofilling-forms-with-javascript/

这是单选按钮的解决方案:

document.querySelectorAll('input[type="radio"]').forEach(elt => { 
    if (localStorage.getItem(elt.name) == elt.value) 
        elt.checked = true; 
    elt.addEventListener("change", e => { 
        localStorage.setItem(e.target.name, e.target.value); 
    }); 
});

这适用于文本 <input>