(() => {
localStorage.setItem("Checkboxes", "{}");
const cbDiv = document.querySelector("#chkBoxes");
const fancyReporting = reportingFactory();
// save the state of a checkbox clicked
// used by the click handler on 'document'
const saveCheckboxState = (val, id) => {
localStorage.setItem("Checkboxes",
JSON.stringify({
...JSON.parse(localStorage.getItem("Checkboxes")),
[`Checkbox ${id}`]: +val })
);
fancyReporting.showCurrentCheckboxStates();
};
// add a handler to the document
// it's using event delegation
document.addEventListener("click", evt =>
// if the element has a property 'data-index', go ahead
// otherwise do nothing
evt.target.dataset.index &&
saveCheckboxState(evt.target.checked, evt.target.dataset.index)
);
// create 10 checkboxes for demo
// for every checkbox, save initial state in localStorage
for (let i = 1; i < 11; i += 1) {
let cb = document.createElement('input');
cb.type = 'checkbox';
cb.dataset.index = i;
cb.title = `Checkbox ${i}`;
cbDiv.appendChild(cb);
// save the state using the method for it
saveCheckboxState(0, i);
}
// just for reporting
function reportingFactory() {
return {
state: {
checked: String.fromCharCode(9745),
unchecked: String.fromCharCode(9744)
},
result: document.querySelector("pre"),
showCurrentCheckboxStates() {
const states2Report = Object.fromEntries(
Object.entries(JSON.parse(localStorage.getItem("Checkboxes")))
.map( ([key, value]) => ([key, value < 1 ? this.state.unchecked : this.state.checked]) )
);
this.result.textContent = `Checkboxes localStorage saved state: ${
JSON.stringify(states2Report, null, " ")}`
.replace(/"|{|}/g, "") + `\nlocalStorage literal value:\n${
JSON.stringify(localStorage)}`
}
};
}
})();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.