简体   繁体   中英

Populate form with localStorage

I'm building a webapp where I have a settings panel. I have a code that saves data from form to localStorage, but how could I make it populate the form automatically on pageload if there is some data saved to localStorage?

This is my code for the form:

<label for="serveri"> Server: </label> 
<input type='text' name="server" id="saveServer"/> 
<button onclick="save_data()" type="button" value="Save" id="Save" data-theme="a">Save</button> 

<script> function save_data()
{ var input = document.getElementById("saveServer");
localStorage.setItem("server", input.value); 
var storedValue = localStorage.getItem("server"); } 
</script> 

All you need to do is add a ready method to load the data.

$(document).ready(function() {
  $(input[name=server]).val(localStorage.getItem("server"));
});

Or non- JQuery answer.

function save_data() {
  // Save functionality here...
}

function load_data() {
  var input = document.getElementById("saveServer");
  input.value = localStorage.getItem("server");
}

load_data();

Just make sure your form exists before any of the JavaScript to populate it is executed.

Here is a working example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM