javascript - Store multiple checkbox inputs in local storage - Stack Overflow

I have multiple checkbox inputs that look like this:<input type="checkbox" id="box-1&

I have multiple checkbox inputs that look like this:

<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">

I want to store their values (checked or unchecked) in the browser's local store.

The javascript that I'm using to do this is:

function onClickBox() {
  let checked = $("#box-1").is(":checked");
  let checked = $("#box-2").is(":checked");
  let checked = $("#box-3").is(":checked");
  localStorage.setItem("checked", checked);
}

function onReady() {
  let checked = "true" == localStorage.getItem("checked");
  $("#box-1").prop('checked', checked);
  $("#box-2").prop('checked', checked);
  $("#box-3").prop('checked', checked);

  $("#box-1").click(onClickBox);
  $("#box-2").click(onClickBox);
  $("#box-3").click(onClickBox);
}

$(document).ready(onReady);

The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.

This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.

I have multiple checkbox inputs that look like this:

<input type="checkbox" id="box-1">
<input type="checkbox" id="box-2">
<input type="checkbox" id="box-3">

I want to store their values (checked or unchecked) in the browser's local store.

The javascript that I'm using to do this is:

function onClickBox() {
  let checked = $("#box-1").is(":checked");
  let checked = $("#box-2").is(":checked");
  let checked = $("#box-3").is(":checked");
  localStorage.setItem("checked", checked);
}

function onReady() {
  let checked = "true" == localStorage.getItem("checked");
  $("#box-1").prop('checked', checked);
  $("#box-2").prop('checked', checked);
  $("#box-3").prop('checked', checked);

  $("#box-1").click(onClickBox);
  $("#box-2").click(onClickBox);
  $("#box-3").click(onClickBox);
}

$(document).ready(onReady);

The first part saves the checkbox's state on the click and the second part loads it when the page refreshes.

This works well if the lines for box 2 and 3 are removed, but I need it to work with all the checkboxes.

Share edited Jul 26, 2018 at 16:24 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jul 26, 2018 at 16:13 Adam ScotAdam Scot 1,4094 gold badges26 silver badges43 bronze badges 1
  • 4 You are redeclaring the same variable (checked) three times in the top function. If all three checkboxes have different states you will have to store them individually or as a bit mask. – Marie Commented Jul 26, 2018 at 16:16
Add a ment  | 

4 Answers 4

Reset to default 7

Your main issue here is that you're only storing a single value in localStorage, checked, which will be overwritten every time you check a different box. You instead need to store the state of all boxes. An array is ideal for this, however localStorage can only hold strings, so you will need to serialise/deserialise the data when you attempt to read or save it.

You can also simplify the logic which retrieves the values of the boxes by putting a mon class on them and using map() to build the aforementioned array. Try this:

<input type="checkbox" id="box-1" class="box" />
<input type="checkbox" id="box-2" class="box" />
<input type="checkbox" id="box-3" class="box" />
jQuery($ => {
  var arr = JSON.parse(localStorage.getItem('checked')) || [];
  arr.forEach((c, i) => $('.box').eq(i).prop('checked', c));

  $(".box").click(() => {  
    var arr = $('.box').map((i, el) => el.checked).get();
    localStorage.setItem("checked", JSON.stringify(arr));
  });
});

Working example

  function onClickBox() {
        let checked1 = $("#box-1").is(":checked");
        let checked2 = $("#box-2").is(":checked");
        let checked3 = $("#box-3").is(":checked");
        localStorage.setItem("checked1", checked1);
        localStorage.setItem("checked2", checked2);
        localStorage.setItem("checked3", checked3);
    }


    function onReady() {

        let checked1 = "true" == localStorage.getItem("checked1");
        let checked2 = "true" == localStorage.getItem("checked2");
        let checked3 = "true" == localStorage.getItem("checked3");
        $("#box-1").prop('checked', checked1);
        $("#box-2").prop('checked', checked2);
        $("#box-3").prop('checked', checked3);

        $("#box-1").click(onClickBox);
        $("#box-2").click(onClickBox);
        $("#box-3").click(onClickBox);

    }

    $(document).ready(onReady);

Of course you could simplify it further by doing

    function onClickBox(boxNumber) {
        let checked = $("#box-" + boxNumber).is(":checked");
        localStorage.setItem("checked" + boxNumber, checked);
    }

    function onReady() {
        [1, 2, 3].forEach( function(boxNumber) { 
          $("#box-" + boxNumber).prop(
            'checked', 
            localStorage.getItem("checked" + boxNumber)
          );
          $("#box-" + boxNumber).click( function() {
            localStorage.setItem(
              "checked" + boxNumber,  
              $("#box-" + boxNumber).is(":checked")
            );
          });
        })
    }

    $(document).ready(onReady);

Your check variable is getting overwritten, you can put it inside for loop. So your code bees,

function onClickBox() {
 for(var i=1;i<=3;i++){
       let checked=$("#box-"+i).is(":checked");
       localStorage.setItem("checked-"+i, checked);
    }
 }


function onReady() {
   for(var i=1;i<=3;i++){
     if(localStorage.getItem("checked-"+i)=="true"){
      var checked=true;
     }
     else{
      var checked=false;
     }
    $("#box-"+i).prop('checked', checked);
    onClickBox();
   }
}

$(document).ready(onReady);

Please follow the below Code (Very Simple Javascript works)

<input type="checkbox" id="box">checkbox</input>
<button type="button" onClick="save()">save</button>
<script>
function save() {   
    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>

with simple modification, you can use it without save button.. Hope this Helps you..

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743690547a4490890.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信