-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersist.js
More file actions
23 lines (20 loc) · 974 Bytes
/
Copy pathpersist.js
File metadata and controls
23 lines (20 loc) · 974 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
// set unique id for each checkbox
checkbox.id = escape(checkbox.nextSibling.textContent.trim().replace(/\s+/g, '_')).replace(/[^\w]+/g, '_');
// enable labeling for easy checking
checkbox.insertAdjacentHTML('afterend', `<label for="${checkbox.id}">${checkbox.nextSibling.textContent}</label>`);
// remove textContent for readability
checkbox.nextSibling.nextSibling.remove();
checkbox.onchange = () => {
if(!checkbox.checked)
delete checkboxValues[checkbox.id];
else
checkboxValues[checkbox.id] = true;
localStorage.setItem('checkboxValues', JSON.stringify(checkboxValues));
};
});
// restore previous state
for(let i in checkboxValues){
document.querySelector(`#${i}`).setAttribute('checked', true);
}