Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

html - Save input data to localStorage on button click

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.

<input type='text' name="server" id="saveServer"/>  

How can I save data from input to localStorage when user clicks the button? Something like this?

<input type='text' name="server" id="saveServer"/>  

<button onclick="save_data()" type="button">Save/button>

    <script>
            function saveData(){
        localStorage.saveServer
        }
        </script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The localStorage object has a setItem method which is used to store an item. It takes 2 arguments:

  1. A key by which you can refer to the item
  2. A value

    var input = document.getElementById("saveServer");
    localStorage.setItem("server", input.val());
    

The above code first gets a reference to the input element, and then stores an item ("server") in local storage with the value of the value of that input element.

You can retrieve the value by calling getItem:

var storedValue = localStorage.getItem("server");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...