【问题标题】:Serialize a form to localStorage / restore it after page reload (without jQuery)将表单序列化到 localStorage / 在页面重新加载后恢复它(没有 jQuery)
【发布时间】:2020-07-26 22:10:16
【问题描述】:

我有一个 <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,然后在页面重新加载时(例如在我们关闭并重新打开浏览器后)重新加载之前选择的项目?

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

我们可能必须为事件“选择单选按钮”分配一个侦听器,还是应该简单地通过“更改”事件来检测?

注意:这解决了&lt;input type="text"&gt; 的类似问题:Auto-save all inputs value to localStorage and restore them on page reload

也许有更简单的方法:

我们能否将一个整个 &lt;form&gt; 状态(输入值、选中的单选按钮等)序列化为 localStorage,并在不使用 jQuery 的情况下轻松恢复它? (无需为文本输入编写特定代码、为单选按钮编写其他代码、为复选框编写其他代码等)

【问题讨论】:

  • 致反对者:您能否添加评论来解释如何改进这个问题?
  • 你使用 localStorage.setItem('key', value) 和.getItem('key')。 stackoverflow.com/questions/17087636/…
  • @JoelHager 这对于&lt;input&gt; 单选按钮组来说并不那么简单。是否有通用的解决方案来序列化整个&lt;form&gt;,无论内容(收音机、复选框、文本等)如何?
  • 可能是这样的? telerik.com/blogs/…

标签: javascript html forms radio-button local-storage


【解决方案1】:
  1. 创建一个辅助函数来检索表单值:https://stackoverflow.com/a/41262933/4988674

  2. 为表单更改添加事件监听器:https://stackoverflow.com/a/10760931/4988674

  3. 内部事件监听器将表单数据保存到localStorage:https://stackoverflow.com/a/2010948/4988674

  4. 创建“onload”事件并从 localStorage 填充表单值:https://stackoverflow.com/a/7327185/4988674https://benalexkeen.com/autofilling-forms-with-javascript/

【讨论】:

【解决方案2】:

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

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); 
    }); 
});

这适用于文本&lt;input&gt;Auto-save all inputs value to localStorage and restore them on page reload

【讨论】:

  • 我建议运行“formElement.querySelectorAll”而不是“document.querySelectorAll”,因为它只会影响表单内的输入,而不是页面上的所有输入。
猜你喜欢
  • 2020-07-19
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2014-09-20
相关资源
最近更新 更多