mercredi 2 mars 2022

JS Remember me checkbox - info not being recalled

I have the following code as below. The issue is that when I have it in the on the html page the code works fine and when I reload the page the values are prefilled in the input field.

But when I move it to the tools.js file, the fields fail to pre=populate on the form. I would like them to be pre populated on return later.

Any ideas:

<div>
     <label>
     <input type="checkbox" id="customerRemember"  name="remember" > Remember me
     </label><br>
</div>

<input type="submit" id="submitButton" value='Submit'>

and

<script>

// Code to remember user details when remember me option checked on checked fiel------///
const rmCheck = document.getElementById("customerRemember"),
    nameInput = document.getElementById("name"),
    mobileInput = document.getElementById("mobile"),
    emailInput = document.getElementById("email");

if (localStorage.checkbox && localStorage.checkbox !== "") {
  rmCheck.setAttribute("checked", "checked");
  nameInput.value = localStorage.username;
  mobileInput.value = localStorage.usermobile;
  emailInput.value = localStorage.useremail;
} else {
  rmCheck.removeAttribute("checked");
  nameInput.value = "";
  mobileInput.value = "";
  emailInput.value = "";
}

submitButton.onclick =function() {
  if (rmCheck.checked && emailInput.value !== "") {
    localStorage.username = nameInput.value;
    localStorage.usermobile = mobileInput.value;
    localStorage.useremail = emailInput.value;
    localStorage.checkbox = rmCheck.value;
  } else {
    localStorage.username = "";
    localStorage.usermobile = "";
    localStorage.useremail = "";
    localStorage.checkbox = "";
  }
}
</script>



Aucun commentaire:

Enregistrer un commentaire