Question

I have a problem with localStorage and am trying to make it store a value, if there is no localStorage value in the textbox, it should say First Try. Here's the code:

JavaScript:

// 1. onload - Fill the textbox named "myData" with data from local storage variable called
// 'myData'. If no local storage is available, fill the textbox with the words "First Try". If there is a value then, keep it. So, when the page refreshes it will still be there in the textbox.  
    function loadIt() {
        var myData = document.getElementById("myData");
        // place content from previous edit
        if (!myData.value) 
        {
          myData.value = window.localStorage.getItem('value');
        }

        // your content will be saved locally
         window.localStorage.setItem('value', myData.value);

HTML:

<input type="text" id="myData" value=""/>
Was it helpful?

Solution

In the onload event you should read the local storage and set it in the textbox there is a value stored, otherwise make it "First try".

window.onload = function(){
      var val = localStorage.getItem('value'); // or localStorage.value

      if(val == null)
          val = "First try";

     document.getElementById("myData").value = val;
}

In the onbeforeunload event you should retrieve the value of the textbox and save it in the local storage.

window.onbeforeunload = function(){
    localStorage.setItem('value', document.getElementById("myData").value); // or  localStorage.value = document.getElementById("myData").value
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top