Home > Back-end >  Local storage not working when i add if statement
Local storage not working when i add if statement

Time:09-01

Hello i have problem with my local storage. When i add if (checkBox.checked == true) after that its not working. When i remove it is working again. Can you please help me. VSC write this : "saveToLocalStorage" is declared but its value is never read. Here is js code :

 
const storageInput = document.getElementById("oknotext");
const text = document.getElementById("stavtrate");
const button = document.getElementById("akt");
const storedInput = localStorage.getItem("textinput");
const checkBox = document.getElementById("robot");


if (storageInput) {
  text.textContent = storedInput;
}

storageInput.addEventListener("input", (letter) => {
  text.textContent = letter.target.value;
});
if (checkBox.checked == true) {
  const saveToLocalStorage = () => {
    localStorage.setItem("textinput", text.textContent);
  };
}

button.addEventListener("click", saveToLocalStorage);

Html


      <p id="uvodstav">Aktuálny stav trate:</p>
      <p id="stavtrate">zatiaľ neaktualizovaný</p>
      <p id="datum">0.00.0000</p>
      <p>
        Stav trate:
        <input
          type="text"
          name="message"
          maxlength="160"
          id="oknotext"
          required
        />
        <input name="submit" type="submit" value="Aktualizovať" id="akt" />
      </p>
      <p>
        <input type="checkbox" id="robot" required /><label for="robot"
          >Nie som robot</label
        >
      </p>

CodePudding user response:

Check if the checkbox is checked inside of the saveToLocalStorage function.

const saveToLocalStorage = () => {
  if (checkBox.checked === true) {
    localStorage.setItem("textinput", text.textContent);
  }
};

button.addEventListener("click", saveToLocalStorage);
  • Related