JSFiddle - React, Tailwind, and code Playground
HTML
<form action="">
<input type="checkbox" name="earth">
<input type="checkbox" name="water">
<input type="checkbox" name="fire">
<input type="checkbox" name="wind">
</form>
JavaScript
const state = {
fields: ['earth', 'water', 'fire', 'wind'],
form: null,
saveState() {
const state = {};
for (let field of this.fields) {
state[field] = this.form[field].checked;
}
try {
localStorage.setItem('state', JSON.stringify(state));
} catch (e) {
return;
}
},
loadState() {
try {
const state = JSON.parse(localStorage.getItem('state'));
if (!state) {
return;
}
for (let field of this.fields) {
this.form[field].checked = state[field];
}
} catch (e) {
return;
}
},
init() {
this.form = document.querySelector('form');
if (!this.form) {
return;
}
this.form.addEventListener('change', this.saveState.bind(this));
this.loadState();
}
};
state.init();