I’m trying to do a simple personal website with checkboxes implemented into it, I’ve never done anything to do with coding ever so I’m super confused on how to put it all together. So far I have a checkbox labeled as purchased, but after I check the box and refresh the page it’s like I never checked the box. I was reading that I need local storage implemented into the code for my changes to save even after refreshing the page. But I have no idea how it should be done and what exactly I need to type in, if anyone could leave what it’s supposed to look like that would be great, thank you genuinely! What I have so far:
<label >
<input type="checkbox" name="purchased" />
Purchased
</label>
CodePudding user response:
You can implement a persistent checkbox using local storage like this:
const cb = document.getElementById('checkbox');
//run every time the checkbox is set
cb.addEventListener('input', (e) => {
console.log('changed');
localStorage.setItem('purchased', e.target.checked);
});
//run once on page load, check if it is set in LS if yes then check it
const localPurchasedValue = localStorage.getItem('purchased');
if (localPurchasedValue === 'true') {
cb.checked = true;
}
<label >
<input id="checkbox" type="checkbox" name="purchased" />
Purchased
</label>
Note this little preview will not work due to iframe restrictions on this site, but if you copy this into your own file and run with a dev server or some kind you can see it working.
CodePudding user response:
"... but after I check the box and refresh the page it’s like I never checked the box..."
Hi, according comments is necessary to save into some type storage.
Look like this:
let boxes = document.getElementsByClassName('box').length;
function save() {
for(let i = 1; i <= boxes; i ){
var checkbox = document.getElementById(String(i));
localStorage.setItem("checkbox" String(i), checkbox.checked);
}
}
//for loading
for(let i = 1; i <= boxes; i ){
if(localStorage.length > 0){
var checked = JSON.parse(localStorage.getItem("checkbox" String(i)));
document.getElementById(String(i)).checked = checked;
}
}
window.addEventListener('change', save);
<input type="checkbox" id="1" >checkbox1</input><br>
<input type="checkbox" id="2" >checkbox2</input><br>
<input type="checkbox" id="3" >checkbox3</input><br>
<input type="checkbox" id="4" >checkbox4</input><br>
<input type="checkbox" id="5" >checkbox5</input><br>
<input type="checkbox" id="6" >checkbox6</input><br>