Home > Back-end >  Change input position after page refresh
Change input position after page refresh

Time:12-08

I tried to save position of the input element using localStorage. I saved 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 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);
});

CodePudding user response:

You just need to check the checkbox is checked or not. If checkbox is checked make localstorage otherwise remove localstorage.

Here down is example:

<!DOCTYPE html>
<html>
<body>

<div class="switch">
  <input type="checkbox" id="c1">
  <label for="c1"><span id="chkcheck"></span></label>
</div>


<script>
const chk = document.getElementById('c1');
window.onload = function(){
    var storedPosition = localStorage.getItem('saved');
    if(storedPosition != null)
    {
        chk.setAttribute("checked", "checked");
    }
    console.log(storedPosition);
};

chk.addEventListener("change", () => {
  if(chk.checked){
    chk.setAttribute("checked", "checked");
    localStorage.setItem("saved","saved");
  }else{
    chk.removeAttribute("checked");
    localStorage.removeItem('saved');
  }
});
</script>

</body>
</html>

CodePudding user response:

for input elements the value attribute controls the initial value of an element so it makes sense it will reset when the page is refreshed, but if the js script isn't changing the value of the input to the stored value, make sure you are using it in your html script with something like

<script src="index.js"></script>

if you are already doing this I probably can't be of much help since otherwise it looks correct to me

  • Related