0

I have a simple js code, and it add some data and save it on some HTML tag, can I add this to localstorage and save it on some time of sesion. Can someone tell, how I can save data on localstorage? Thank you a lot of times for advance.

        function addComment()
            {
              var vname = document.getElementById("vname").value;
              var li = document.createElement('li');
              li.innerText = vname;
              document.getElementById('comments').appendChild(li);
              document.getElementById("vname").value = '';
              document.getElementById("vname").focus();
            }
        function addAuthor()
        {
            var author = document.getElementById("author").value;
            var li = document.createElement('li');
            li.innerText = author;
            document.getElementById('comments').appendChild(li);
            document.getElementById("author").value = '';
            document.getElementById("author").focus();
        }
        <label for="vname">Name of your book</label>
        <input type="text" id="vname" name="vname">
        <input type="submit" value="Add name" onclick="addComment()">
        <br>
        <label for="author">Author of book</label>
        <input type="text" id="author" name="author">
        <input type="submit" value="Add author" onclick="addAuthor()">

<ul id="comments"></ul>
Nazariy
  • 23
  • 5
  • 2
    Possible duplicate of [How to save data from a form with HTML5 Local Storage?](https://stackoverflow.com/questions/17087636/how-to-save-data-from-a-form-with-html5-local-storage) – brk Aug 19 '17 at 03:12

2 Answers2

0

you can set values in localStorage like this

localStorage.setItem("name", "value");

or

window.localStorage.setItem("name", "value");

you can append value like this

var value  = localStorage.getItem("name");
$("#div_id").text(value);

OR for input field

$("#input_field_id").val(value);

or

window.localStorage.getItem("name");

i this window.localStorage is for angularjs bu i am not sure

Anil Shrestha
  • 1,180
  • 11
  • 16
0

first you need to check your browser support or not localStorage

   if (typeof(Storage) !== "undefined") {
    //if your browser support localstorage then you can write code like this

    localstorage.setItem("your key", JSON.stringify(your value));

} else {
// sorry you can't use localstorage

}

after you set your value

you can access your value like this way

var your_variable = JSON.parse(localstorage.getItem("your key"));
md. motailab
  • 52
  • 1
  • 8