Let's assume our checkboxes are blind
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
<input type="checkbox" onclick = "clickThis(event)" value="Yes"/>
Now we need to find out which element was clicked, for this we can get the index of the element which is clicked.
const clickedIndex = [...event.target.parentElement.children].indexOf(event.target);
this line will gives you the index of clicked element which you can save in your localstorage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
and also you can check whenever your page load that which index is saved in your localstorage.
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
hence the complete code
<body>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
<input type = "checkbox" onclick = "clickThis(event)"/>
</body>
<script>
const inputs = document.querySelectorAll("input");
console.log(inputs);
if (localStorage.length > 0) {
for (let key in localStorage) {
if (!isNaN(localStorage[key]))
inputs[localStorage[key]].checked = true;
}
}
function clickThis(event) {
console.log(event.target);
const el = event.target;
const clickedIndex = [...el.parentElement.children].indexOf(el);
if (event.target.checked) {
// adding click value to local storage
localStorage.setItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
} else {
// deleting unchecked value from localstorage
localStorage.removeItem([...el.parentElement.children].indexOf(el), [...el.parentElement.children].indexOf(el));
}
}
</script>
#happy_coding
REPL link
https://repl.it/repls/SlateblueCorruptScale