Reputation: 51
I have a list of tasks if you will and I am trying to create checkboxes that persist next to each when I go back to the page but closing the browser or hard refresh kills my selections. I have found code for saving a single checkbox but how do I iterate through the different boxes and keep them next time I enter? It seems like a really simple process but I am super-new to javascript... I could do this easily in vbscript but I would like it to work everywhere and not just IE!
New to all this so be gentle please.
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
// then enter variation of the code I found here
<script >
function save() {
//enter iteration sequence
var checkbox = document.getElementById("box");
localStorage.setItem("box", checkbox.checked);
}
//for loading...
var checked = JSON.parse(localStorage.getItem("box"));
document.getElementById("box").checked = checked; <
/script>
Upvotes: 3
Views: 2325
Reputation: 1482
To retrieve all elements you can use document.querySelectorAll
and pass as argument the filter that will do the job. In this case you want to retrieve all htlm
elements that have the type
attribute value equals to checkbox
. After the retrieval of all elements that have type="checkbox"
, you should traverse all elements of list. And for each element you should store the id of checkbox as key
and the checked
of the checkbox asvalue
in localstorage.
Below is the code:
<script>
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
And below is the code for updating the checkboxes with value we stored in localstorage.
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
If you want to use cookie to store the information instead of local storage. Link for more information: https://www.guru99.com/cookies-in-javascript-ultimate-guide.html.
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
VERSION WITH LOCAL STORAGE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(localStorage.getItem(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
localStorage.setItem(el.id, el.checked);
console.log(el.id,el.checked);
})
}
</script>
</body>
</html>
VERSION WITH COOKIE
<html>
<head>
</head>
<body>
<div>
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="checkbox" id="whatever-3" />This task
<input type="checkbox" id="whatever-4" />This task
<input type="checkbox" id="whatever-5" />This task
<input type="button" value="Save" onclick="save();" />
</div>
<script>
window.onload= function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
var checked = JSON.parse(accessCookie(el.id));
document.getElementById(el.id).checked = checked;
});
}
save = function(){
var list = document.querySelectorAll(`[type*="checkbox"]`);
list.forEach( el => {
createCookie(el.id, el.checked,1);//1 is the day to expire
console.log(el.id,el.checked);
})
}
function createCookie(cookieName, cookieValue, daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for (var i = 0; i < allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name) == 0)
return temp.substring(name.length, temp.length);
}
return "";
}
</script>
</body>
</html>
Upvotes: 5
Reputation: 89
Your code works well too if you pass right id's of inputs but there is an issue with it that for each and every input you have to add there variable you also can use for loop for that.
Your code with fixing script
<input type="checkbox" id="whatever-1" />This task
<input type="checkbox" id="whatever-2" />This task
<input type="button" value="Save" onclick="save();" />
<script>
function save() {
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checkbox2 = document.getElementById("whatever-2");
localStorage.setItem("whatever-2", checkbox2.checked);
}
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
var checked = JSON.parse(localStorage.getItem("whatever-2"));
document.getElementById("whatever-2").checked = checked;
</script>
Upvotes: 0
Reputation: 4346
On every save
you can create an object with checkbox identification and values, save t in localStorage
, on reloading, get the the whole object by a single key, parse it, loop through and set values
function save() {
//enter iteration sequence
var checkboxes = document.querySelectorAll("input[type=checkbox]");
var obj = {};
for (i = 0; i < checkboxes.length; i++) {
obj[checkboxes[i].id] = checkboxes[i].checked
}
localStorage.setItem("box", JSON.stringify(obj));
}
//for loading...
var checkboxesValues = JSON.parse(localStorage.getItem("box"));
Object.keys(checkboxesValues).map(key => document.getElementById(key).checked = checkboxesValues[key]);
Upvotes: 0
Reputation: 1899
Just pass a different id in to document.getElementById
.
Make sure to use a different key for localStorage.setItem
so you don't overwrite a different value.
var checkbox = document.getElementById("whatever-1");
localStorage.setItem("whatever-1", checkbox.checked);
var checked = JSON.parse(localStorage.getItem("whatever-1"));
document.getElementById("whatever-1").checked = checked;
You could do this individually for each item or you could get all the elements of a specific class. Then loop through the elements and use their id as the local storage key.
Alternatively you could use a for
loop and loop for as many items as you wish to save
Upvotes: 1