Reputation: 1298
I have 6 checkboxes on my HTML page. Upon form submission, I want to save in localStorage which ones are checked and which ones are not checked. This is my code:
var getmealpref;
for(var i=0, l=checkboxes.length; i<l;i++)
{
if(checkboxes[i].checked)
{
localStorage.setItem('mealpref',checkboxes[i].value);
getmealpref[i] = localStorage.getItem('mealpref');
alert(getmealpref[0])
okay=true;
}
}
I think I am trying to achieve it the wrong way. Is there any method of defining an array for localStorage.getItem?
Upvotes: 0
Views: 1052
Reputation: 2103
You must serialize non-string types before storing in localStorage.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var getmealpref = [];
for(var i=0, l=checkboxes.length; i<l;i++) {
if(checkboxes[i].checked) {
getmealpref[i] = checkboxes[i].value;
localStorage.mealpref = JSON.stringify(getmealpref);
}
}
// debug
getmealpref = JSON.parse(localStorage.mealpref);
alert(getmealpref[0]);
JSFiddle: http://jsfiddle.net/UD4Bk/2
Upvotes: 1
Reputation: 318182
localStorage will accept arrays, but they will be stored as strings so you're better off storing JSON
var getmealpref = [];
for(var i=0, l=checkboxes.length; i<l;i++) {
getmealpref[i] = checkboxes[i].checked;
}
localStorage.setItem('getmealpref', JSON.stringify(getmealpref));
to reset them to the stored values
var values = JSON.parse( localStorage.getItem('getmealpref') );
for(var i=0, l=checkboxes.length; i<l;i++) {
checkboxes[i].checked = values[i];
}
Upvotes: 0