Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 509
user1358625 Avatar asked Apr 26 '12 12:04

user1358625


People also ask

How do I save a string in localStorage?

The localStorage can store only strings. To store objects, you convert them to strings using the JSON. stringify() method. And you convert the strings into objects when you retrieve them from the localStorage using the JSON.

Can localStorage be hacked?

If an attacker can run JavaScript on your website, they can retrieve all the data you've stored in local storage and send it off to their own domain. This means anything sensitive you've got in local storage (like a user's session data) can be compromised.


2 Answers

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");
like image 105
James Allardice Avatar answered Oct 02 '22 03:10

James Allardice


This worked for me. For setting I placed .value behind the var and called the var in the setItem:

var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);

For getting the text back:

document.getElementById('saveServer').value = localStorage.getItem('server');
like image 34
Stephan Avatar answered Oct 02 '22 03:10

Stephan