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...?
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.
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!
You can
store the value in memory, using JS
var arr = [];
arr.push(your_value);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With