0

I'm trying to store oninput event listener value in the local storage of the web browser. For example: if I'm typing something in a form input field it should be stored in local storage and when I refresh the page it should still be there. I read several blogs and watched tutorials on local storage and did the same but it isn't working for me. Can anyone please point out the mistake and how can I fix that?

Thanks in Advance!

<form class="form" action="https://formspree.io/f/meqvlgqr" method="POST">
    <input
      type="text"
      name="name"
      maxlength="30"
      placeholder="Full Name"
      required
      class="input"
    />
    <input
      type="email"
      name="email"
      placeholder="example@gmail.com"
      required
      class="input"
    />
    <textarea
      rows="4"
      cols="50"
      name="message"
      placeholder="Write your message here ..."
      required
      maxlength="500"
      class="input-textarea"
    ></textarea>
    <button type="submit" class="contact-button">Get It Touch</button>
  </form>

oninput value is being displayed on inspector tool in console tab but when I go to application tab and check storage it displayed the JSON object but its values are empty.

const storeName = document.querySelector('input[type=text]');
const storeEmail = document.querySelector('input[type=email]');
const storeMessage = document.querySelector('.input-textarea');
const userDetails = { name: '', email: '', message: '' };

storeName.addEventListener('input', (e) => {
  userDetails.name = e.target.value;
  console.log(userDetails.name);
});

localStorage.setItem('userDetails', JSON.stringify(userDetails));
Zain Sadaqat
  • 85
  • 10
  • 1
    Put `setItem` _inside_ the event listener? Of course if you put it outside it won't register anything – Jeremy Thille Jul 30 '21 at 07:31
  • Wooh ..., I did and now the values started getting stored in the local storage. Thanks, man I'm trying this since yesterday and I couldn't figure that out. – Zain Sadaqat Jul 30 '21 at 07:35
  • But now when I refresh the page, the values disappear. How can I make them stay there even I refresh or close the browser window? – Zain Sadaqat Jul 30 '21 at 07:37

1 Answers1

1

you must put local storage setItem action inside of input event listener

 const storeName = document.querySelector('input[type=text]');
 const storeEmail = document.querySelector('input[type=email]');
 const storeMessage = document.querySelector('.input-textarea');
 const userDetails = { name: '', email: '', message: '' };
 
 storeName.addEventListener('input', (e) => {
   userDetails.name = e.target.value;
   console.log(userDetails.name);
   localStorage.setItem('userDetails',JSON.stringify(userDetails));
 });

or for optimizing performance, put it inside form submit event listener

document.querySelector('.form').addEventListener('submit',function(evt){
  evt.preventDefault();
  localStorage.setItem('userDetails', JSON.stringify(userDetails));
})
Ali
  • 36
  • 4