Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  98] [ 3]  / answers: 1 / hits: 16520  / 9 Years ago, mon, april 20, 2015, 12:00:00

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


This is the javascript I have:



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


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



And



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


(which runs on document being loaded)



I get the following error: Uncaught TypeError: Cannot set property 'value' of null



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.



Thanks!


More From » html

 Answers
25

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


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



Here is a demo


[#66988] Saturday, April 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;