I tried to save the position of the input element using localStorage. I saved the position of my input element and after page reload I can access it but it's always in default position after page refresh. (Value true/false)
HTML:
<div class="switch">
<input type="checkbox" value="false" id="c1">
<label for="c1"><span></span></label>
</div>
JS:
const chk = document.getElementById('c1');
var storedPosition = localStorage.getItem('saved');
console.log("Saved input value: " + storedPosition);
chk.addEventListener("change", () => {
if(chk.value === "false"){
chk.value = "true";
console.log(chk.value);
}else{
chk.value = "false";
console.log(chk.value);
}
localStorage.setItem('saved',chk.value);
});
To be clear I am creating a chrome extension (options-page).
EDIT:
const chk = document.getElementById('c1');
var storedPosition = localStorage.getItem('saved');
console.log("Saved input value: " + storedPosition);
chk.value = storedPosition; //edited set different value
chk.addEventListener("change", () => {
if(chk.value === "false"){
chk.value = "true";
console.log(chk.value);
}else{
chk.value = "false";
console.log(chk.value);
}
localStorage.setItem('saved',chk.value);
});
Primarily you should use checked instead of value. While checked is the (visual) checked state of the input, value is the value which gets posted.
Also you can make it more simple by storing the value in localStorage as number "0" or "1" which can easily be converted back to a boolean.
window.onload = function(){
const chk = document.getElementById('c1');
//REM: Changed "saved" to the id of the element
//REM: Also in the change listener to make it more dynamic
const storedPosition = localStorage.getItem(chk.id);
console.log("Saved input value: " + !!+storedPosition);
//REM: Use the property "checked" and not the "value"
//REM: Be aware that the value is a string with either null, "0" or "1"
//REM: which can be converted to a number (0 or 1)
chk.checked = +storedPosition;
//REM: Change event
chk.addEventListener("change", () => {
//REM: Use the property "checked" and not the "value"
//REM: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
//REM: Store the boolean as a number to spare conversions
localStorage.setItem(this.id, +this.checked);
//REM: You can omit the rest, unless you want to post it
/*
if(chk.value === "false"){
chk.value = "true";
console.log(chk.value);
}else{
chk.value = "false";
console.log(chk.value);
}
localStorage.setItem('saved',chk.value);
*/
})
}