lundi 3 octobre 2016

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




Aucun commentaire:

Enregistrer un commentaire