Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How i can store javascript array object saved somehow so that I can use it later [duplicate]

Tags:

javascript

I have a situation like follows:

I have a id select page where user can select id from the shown ids on the page.When the user select the id i store them as a comma seperated value in a hidden input field.

      <input type="hidden" values="234,678,987" />

I have a button which on clicking pops up a dialog box which then displays the selected ids. The ids here shown I take from the hidden field. Now I have a requirement to store the product id and name.So probably in this case what should i do because now i can't be able to save this datastructure in hidden input field. Even if i use javascript array ,how can i save that array and use it future for displaying.Is it possible to save array object in hidden input field ....and retrieve it later as array object again...?

like image 813
user882196 Avatar asked Aug 16 '11 23:08

user882196


People also ask

How do you store an array of objects?

To save arrays or objects using the localStorage API in JavaScript, we need to first stringify the arrays or objects using the JSON. stringify() method, and when we need to retrieve the value we can use the JSON. parse() method.


2 Answers

Here's a JSFiddle.

If you want to store the object in an input field, you can use JSON.stringify():

 //Pass your array (or JSON object) into JSON.stringify:
 JSON.stringify([{id:1, product_id: 2, name: 'stack'},
                 {id: 2, product_id: 2, name: 'overflow'}] )

which will yield:

 "[{"id":1,"product_id":2,"name":"stack"},{"id":2,"product_id":2,"name":"overflow"}]"

You can store this value in a hidden field (or a data attribute):

 <input type="hidden" id="project" value="[{'id':1,'product_id':2,'name':'stack"',{'id':2,'product_id':2,'name':'overflow'}]" />

Obviously, you can combine these steps (or do it through PHP / Rails / ...)

 $('#project').val(JSON.stringify([1,2,3]));

You can then decode this using, for instance, jQuery:

 $.parseJSON($('#project').val());

This should allow you to use the process you are using, but store Javascript objects in your input fields. Hope this helps!

like image 155
ghayes Avatar answered Sep 22 '22 21:09

ghayes


You can

  1. store the value in memory, using JS

    var arr = [];
    arr.push(your_value);
    
  2. keep creating new attribute/values in the dom using JS
  3. pass the value from page to page through the query string
  4. store the value in a cookie to be retrieved again
  5. store the value on the server (in a file/db) to retrieve again

Note:
Options 3 and 5 are only meaningful if you want to go to another page (on the site).
Options 4 and 5 are good if you want to close the browser and retrieve that info at a later point.

like image 39
vol7ron Avatar answered Sep 26 '22 21:09

vol7ron