localStorage how to save a checkbox

后端 未结 4 1306
傲寒
傲寒 2020-12-09 12:49

I want to save a checkbox with localstorage. So that when i have checked the box and I close the browser and i re-open it, it will still be checked. right now if i click on

4条回答
  •  抹茶落季
    2020-12-09 12:59

    1). Because boolean true is not equal to string "true". So comparison checked == true is always false, and checkbox never gets checked.

    Instead try this:

    var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
    if (checked == true) {
        document.getElementById("checkbox1zaal1").checked = true;
    }
    

    And remember whatever you store in localStorage is always a string, and only a string. That's why when you save something more complex then primitive value (for example some object) make sure to use JSON.stringify on it first.

    When you retrieve the value from localStorage you should convert it back to it's corresponding javascript type.

    In general load function can also be improved:

    function load(){    
        var checked = JSON.parse(localStorage.getItem('checkbox1zaal1'));
        document.getElementById("checkbox1zaal1").checked = checked;
    }
    

    2). Another problem will come up once you try to uncheck checkbox. You are not handling it currently, so change save function to this one:

    function save(){
        var checkbox = document.getElementById('checkbox1zaal1');
        localStorage.setItem('checkbox1zaal1', checkbox.checked);
    }
    

    Demo: http://jsfiddle.net/Lwxoeyyp/1/

提交回复
热议问题