Store Checkbox 'Checked' with localstorage for multiple items

倖福魔咒の 提交于 2021-01-27 23:51:26

问题


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.getElementById('LineOp');
setStatus.onclick = function() {
    if(document.getElementById('LineOp').checked) {
        localStorage.setItem('LineOp', "true");
    } else {
        localStorage.setItem('LineOp', "false");
    }
}


getStstus = localStorage.getItem('LineOp');
if (getStstus == "true") {
    alert("Welcome Back");
    document.getElementById("LineOp").checked = true;
} else {
    console.log("News");
}

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

function setupBox(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); 
    });
}



回答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



来源:https://stackoverflow.com/questions/24461734/store-checkbox-checked-with-localstorage-for-multiple-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!