I am setting a value checked using localstorage.setitem and using window.location.href to redirect to another page. When page loads and I am trying to acess the saved value using localstorage.getitem, it is not working.
Here is my code:
<input type="checkbox" name="names" onchange="submit(this)" />
function submit(element) {
var names = document.getElementsByName('names');
var selectedList = [];
for (var i = 0; i < names.length; i++) {
if (names[i].checked == true) {
window.localStorage.setItem(names[i].checked, "checked");
}
}
window.location.href = "/testpage.html";
}
$(document).ready(function () {
var names = document.getElementsByName('names');
for (var i = 0; i < names.length; i++) {
if (window.localStorage.getItem(names[i].checked) == "checked") {
names[i].setAttribute('checked', 'checked');
}
}
})
Let's say you're on page x.html and you're redirecting to another page from this page using this line
window.location.href = "/testpage.html";
So any code written in javascript of x.html after the redirecting will not execute, because the execution context of JS now moves to javascript written for testpage.html.
With that said, the solution to your problem will be, to set the localStorage from x.html's JS and when redirected to testpage.html the handle the getting from localStorage part there and then set the values gotten fro localStorage to the checkboxes.
Let's see example of what i've explained above.
Your x.html should look something like this:
function submit(element) {
var names = document.getElementsByName('names');
var selectedList = [];
for (var i = 0; i < names.length; i++) {
if (names[i].checked == true) {
window.localStorage.setItem(names[i].checked, "checked");
}
}
window.location.href = "/testpage.html";
}
<input type="checkbox" name="names" onchange="submit(this)" />
And javascript for testpage.html should look something like this:
$(document).ready(function () {
var names = document.getElementsByName('names');
for (var i = 0; i < names.length; i++) {
if (window.localStorage.getItem(names[i].checked) == "checked") {
names[i].setAttribute('checked', 'checked');
}
}
})