13

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...?

user882196
  • 1,691
  • 9
  • 24
  • 39

4 Answers4

29

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!

hayesgm
  • 8,678
  • 1
  • 38
  • 40
  • well this seems quite good but can i stringify a array object directly or iterate over all the array and create a syntax like above and the stringify...also which library i have to include in jsp page for JSON.Stringify... – user882196 Aug 16 '11 at 23:27
  • JSON.stringify is part of JavaScript now. You'll be able to use it natively. There are plenty of Javascript libraries for parsing JSON, jQuery has one, but there are tons of others. Also, you can stringify an array, JSON will take care of this appropriate. Take a look at this [JSFiddle](http://jsfiddle.net/ghayes/cVxKx/4/) for examples. – hayesgm Aug 16 '11 at 23:30
  • how i can create this format [{id:1, product_id: 2, name: 'stack'}, { id: 2, product_id: 2, name: 'overflow' }]; – user882196 Aug 16 '11 at 23:32
  • From JSP? Maybe [this](http://www.roseindia.net/tutorials/json/json-jsp-example.shtml) will help. Just look up 'JSP JSON' and there's a ton of material on the subject. – hayesgm Aug 16 '11 at 23:34
  • no i mean just in javascript like if i have – user882196 Aug 16 '11 at 23:38
  • var my_cars= new Array() my_cars["cool"]="Mustang"; my_cars["family"]="Station Wagon"; my_cars["big"]="SUV"; – user882196 Aug 16 '11 at 23:39
  • so i just need to do JSON.stringify(my_cars) right... – user882196 Aug 16 '11 at 23:39
  • Yup, that should work. Use `console.log(my_cars);` `console.log(JSON.stringify(my_cars));` and you'll be able to see it in action. – hayesgm Aug 16 '11 at 23:42
  • got here http://stackoverflow.com/questions/4425289/javascript-associative-array-to-json...thanks – user882196 Aug 16 '11 at 23:42
  • Why are you using an associative array as opposed to a JSON object? E.g. my_cars = []; my_cars.push({cool: "Mustang"}); my_cars.push({family: "Station Wagon"}); console.log(my_cars); console.log(JSON.stringify(my_cars)); – hayesgm Aug 16 '11 at 23:44
4

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.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • well i am interested in storing the value in memory.. – user882196 Aug 16 '11 at 23:17
  • tell me more about storing in memory.. – user882196 Aug 16 '11 at 23:18
  • There is nothing more to tell, when you create a javascript array it is stored in memory. It will only be destroyed if it is created within a function, or you go to a different page. In which case you might look at sending the array to the server for handling. – James Hay Aug 16 '11 at 23:19
  • so u r telling me to create some kind of global javascript array... – user882196 Aug 16 '11 at 23:21
  • user882196, yes. If you only need that information while viewing the page, then yes, using a global variable (example number 1) is all you need. `.push()` adds a value to the end of the array and `.pop()` retrieves the values from the end of the array (`.shift()` and `.unshift()` work from the front of the array). – vol7ron Aug 17 '11 at 02:30
  • One more option - localStorage. – andrey.shedko Sep 30 '15 at 08:19
  • @andrey.shedko you're correct. This answer was from 2011, when websql, indexdb and localstorage were all competing for adoption. Localstorage seems to have won – vol7ron Sep 30 '15 at 12:16
  • Local storage and browser cookies (perhaps HTTP cookies — though I wouldn't recommend) are also plausible options. – vol7ron Nov 19 '16 at 21:22
4

If you are not worried about IE7, you can use localStorage:

window.localStorage.setItem('myArray', JSON.stringify([234,678,987]));
// retrieve
var myArray = JSON.parse(window.localStorage.getItem('myArray'));

The JSON is supported by modern browsers. You can add it by including json2.

Joe
  • 80,724
  • 18
  • 127
  • 145
1

I assume you're talking about preserving the data after a new page has loaded. You can use your current approach of storing the data as a string in a hidden input, and then parse that string into a JavaScript object later. Another option is that your server-side code can produce some inline JavaScript declaring the JavaScript object you need. If you're using ASP.NET, for example, your page could have something like this:

// Assuming "serverSideIds" is declared as a List<string>

<% var serializer = new JavaScriptSerializer(); %>
var ids = <%= serializer.Serialize(serverSideIds) %>;
Jacob
  • 77,566
  • 24
  • 149
  • 228