Mark Freid
Mark Freid

Reputation: 49

How do I update input value when page reloads using localstorage?

When a user enters text into the input element, I want to be able to save what they type, so that if they refresh it will still be cached.

const input = document.getElementById('input')
input.onchange = function(){
  const key = input.value;
  localStorage.setItem('key', key)
  input.value = localStorage.getItem("key");
};

Upvotes: 3

Views: 1149

Answers (5)

Mamun
Mamun

Reputation: 68943

Simply assign the value to the input element outside of the event handler function:

const input = document.getElementById('input')
input.value = localStorage.getItem("key"); // get and assign the value outside 
input.onchange = function(){
  const key = input.value;
  localStorage.setItem('key', key);
};

Please Note: You can also consider using oninput instead of onchange.

Upvotes: 3

Anonymous User
Anonymous User

Reputation: 1

First, save the value to localstorage every change. Then, when the page reloads, use localStorage.getItem().

var input = document.getElementById("myinput") // Get my input

function restore(){
  var lst = localStorage.getItem("inputdata") // Get your data from local storage
  
  if(lst === null || lst === undefined){
    return; // return if the user has not visited this site/input
  }
  
  input.value = lst; // Sets the value of the input to the restore data
  
  return;
}

restore()

function save(event_data){
  localStorage.setItem("inputdata",input.value) // Save the value in localStorage
}

input.addEventListener("change",save);
Input Something Here <input id="myinput">

This works but I recommend using cookieStorage for this.

Upvotes: 0

Lead Developer
Lead Developer

Reputation: 1169

<body onload="reloadData()">
 <!-- your html here -->
</body>
<script>
    const input = document.getElementById('input')
    input.onchange = function(){
        const value = input.value;
        localStorage.setItem('key', value);
    };
    function reloadData() {
        input.value = localStorage.getItem('key') || ''
    }
</script>

reloadData function will be invoked when page is load. This will work as you want.

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44105

At the top of your page, add this window.onload statement:

window.onload = function() {
    var data = localStorage.getItem(“key”);
    if (data) {
        document.getElementById(“input”).value = data;
    }
};
// Rest of your code here

Upvotes: 0

Steven Tang
Steven Tang

Reputation: 964

Likely something likes this, just add a load event listener that sets the input value from localStorage or a default value if nothing is in localStorage yet?

const input = document.getElementById('input')
input.onchange = function(){
    const value = input.value;
    localStorage.setItem('key', value);
};

document.addEventListener('load', ()=> {
    input.value = localStorage.getItem('key') || '';
})

Upvotes: 0

Related Questions