Skip to content Skip to sidebar Skip to footer

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

Solution 2:

Since you are using jQuery, try:

var getStstus = localStorage.getItem('LineOp');

if (getStstus === "true")
    $("#LineOp").prop("checked", true);

$("#LineOp").click(function(){
    localStorage.setItem('LineOp', $(this).prop("checked"));
});

jsFiddle

Post a Comment for "Store Checkbox 'checked' With Localstorage For Multiple Items"