0

How can I save html source code into HTML 5 local storage using an array or object.

for example i want to store the following input tags into local storage as an array(here its 3 input tags in 3 array elements) or in object

            <input type="text" class="in1" value="img1">
            <input type="text" class="in2" value="img2">
            <input type="text" class="in3" value="img3"> 

How can I solve this?

3 Answers3

1

Local storage only stores strings in key/value pairs so you won't be able store actual objects or arrays. What you can do is store inputs in a JSON object

  var inputs = {
        0:  '<input type="text" class="in1" value="img1">',
        1:  '<input type="text" class="in2" value="img2">',
        2:  '<input type="text" class="in3" value="img3">'
  }

Then you call:

   JSON.stringify(inputs)

stringify will return a string in a json format and you can store this string to localStorage

To store:

   localStorage.setItem('inputs', JSON.stringify(inputs))

To retrieve the result as an object you will need to use JSON.parse

  JSON.parse(localStorage.getItem('inputs'))
0

Or there is another solution called, sessionvars, don't know the exact site, but if you do a search it can prove very useful for multiwebsite session storage too.

0

I'm not sure why you would, but to answer your question:

HTML:

<div id="container">
    <input type="text" class="in1" value="img1">
    <input type="text" class="in2" value="img2">
    <input type="text" class="in3" value="img3"> 
</div>


Javascript:

localStorage.container = document.getElementById('container').innerHTML;


JSFiddle:
http://jsfiddle.net/jjHTL/

Syntax
  • 2,073
  • 15
  • 15