如何使用纯 Javascript 将选中的单选按钮的值存储在本地存储中? [英] How do you store the value of a checked radio button in local storage using pure Javascript?

查看:42
本文介绍了如何使用纯 Javascript 将选中的单选按钮的值存储在本地存储中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我选中的单选按钮存储在本地存储中,以便在页面重新加载时,它会在重新加载时检查最后一个选中的项目.

I'd like to store my checked radio button in local storage so that on a page reload it will have the last checked item check on the reload.

HTML:

<h3>Seconds Display:</h3>
<p id="secondsHidingText">Hiding seconds extends battery life</p>
&nbsp&nbsp<input type="radio" name="seconds" value="show" checked="checked">Show&nbsp&nbsp
<input type="radio" name="seconds" value="hide">Hide

这是我拥有的 javascript:

This is the javascript I have:

localStorage.setItem('seconds', options.seconds);

(当我点击保存按钮时运行)

(which runs when the save button I have is clicked)

document.getElementById('seconds').value = localStorage.getItem("seconds");

(在正在加载的文档上运行)

(which runs on document being loaded)

我收到以下错误:Uncaught TypeError: Cannot set property 'value' of null

如何在本地存储中存储和检索选中的单选按钮?如果可能的话,我正在寻找一种纯 JS 方式来实现这一点.

How do I store and retrieve the checked radio button to and from local storage? And if possible I'm looking for a pure JS way of accomplishing this.

谢谢!

推荐答案

您必须遍历单选按钮,然后设置值.类似这样的

You would have to iterate through the radio buttons and then set the value. Something like this

var radios = document.getElementsByName("seconds"); // list of radio buttons
var val = localStorage.getItem('seconds'); // local storage value
for(var i=0;i<radios.length;i++){
  if(radios[i].value == val){
      radios[i].checked = true; // marking the required radio as checked
  }
}

我使用 jquery 只是为了方便地设置 localstorage 值.

I used jquery only to set the localstorage value in a convenient way.

这是一个演示

这篇关于如何使用纯 Javascript 将选中的单选按钮的值存储在本地存储中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆