Hexana Hexana - 2 months ago 12
HTML Question

Javascript Save Multiple Checkboxes with LocalStorage

I am trying to save checkboxes with localstorage so that when I refresh the browser, the checked boxes remain persistent until I have clicked a delete button.

Here is what I have tried so far:

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

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

function reload(){
location.reload();
localStorage.clear()
}

load();

<body onload="load()">
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="reload()"/>
<input type="checkbox" id="ch1"></input>

//additional checkboxes
<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch1"></input>

</body>


This is successfully saving one checkbox but I would like to save multiple checkboxes. Therefore I am assuming that I need to I need add a loop in function save() ...

function save(){
var checkbox = document.getElementById('ch1');
for (i = 0; i < checkbox.length; i ++) {
localStorage.setItem('ch1', checkbox.checked);
}
}


However I am a bit stuck on how to get those checked values with the load() call?

Cheers

Answer

You can't have multiple same ID's, they have to be unique.

Then, do like this

function save(){
  // Get all checkbox inputs
  var inputs = document.querySelectorAll('input[type="checkbox"]');
  var arrData = [];
  // For each inputs...
  inputs.forEach(function(input){
    // ... save what you want (but 'ID' and 'checked' values are necessary)
    arrData.push({ id: input.id, checked: input.checked });
  });
  // Save in localStorage
  localStorage.setItem('inputs', JSON.stringify(arrData));

  console.log(JSON.stringify(arrData));
  // [
  //   {
  //     'id': 'ch1',
  //     'checked': false  // or true
  //   },
  //   ... and so on
  // ]
}

function load(){
  var inputs = JSON.parse(localStorage.getItem('inputs'));
  // For each inputs...
  inputs.forEach(function(input){
    // Set the 'checked' value
    document.getElementById(input.id).checked = input.checked;
  });
}


<input type="checkbox" id="ch1"></input>
<input type="checkbox" id="ch2"></input>
<!-- And so on -->
Comments