Store Checkbox 'checked' With Localstorage For Multiple Items
I want to save my checkboxes to localstorage, but this code I am using would be too cumbersome for multiple checkboxes.... is there a better way to do this? setStatus = document.ge
Solution 1:
Here is a way where you could put as many checkboxes as you want, just add the store attribute with a unique identifier for local storage. JSFiddle
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
functionsetupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function() {
localStorage.setItem(storageId, this.checked);
});
}
Post a Comment for "Store Checkbox 'checked' With Localstorage For Multiple Items"