Recipe 7.1

Populating a Form Field From Local Storage

Enter any username and password values, then click “Log In”. The username that you enter will be remembered in local storage. If you refresh the page, the login form will be pre-populated with the username you previously entered.

Demo

You are now logged in! Your username has been remembered in local storage. If you refresh the page, the login form will be populated with your username for you.

Code

JavaScript
const form = document.querySelector('#login-form');

const username = localStorage.getItem('username');
if (username) {
  form.elements.username.value = username;
}

form.addEventListener('submit', event => {
  event.preventDefault();
  
  const data = new FormData(form);
  localStorage.setItem('username', data.get('username'));

  form.classList.add('d-none');
  document.querySelector('#success').classList.remove('d-none');
});
HTML
<form id="login-form">
  <div class="my-4">
      <label for="username">Username</label>
      <input class="form-control" id="username" name="username">
  </div>
  <div class="my-4">
    <label for="password">Password</label>
    <input type="password" class="form-control" id="password" name="password">
  </div>
  <button class="btn btn-primary">Log In</button>
</form>

<div id="success" class="d-none">
  You are now logged in! Your username has been remembered in local storage. If you refresh the page, the
  login form will be populated with your username for you.
</div>
Web API Cookbook
Joe Attardi