Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store return json value in input hidden field

I was wondering if it's possible to store the return json in a hidden input field. For example this is what my json return:

[{"id":"15aea3fa","firstname":"John","lastname":"Doe"}] 

I would like to just store the id in a hidden field so I can reference it later to do something with it.

Example: I have something like this:

<input id="HiddenForId" type="hidden" value="" /> 

and would like jquery to return the value later to me like so:

var scheduletimeid = $('#HiddenForId').val(); 
like image 870
hersh Avatar asked Aug 10 '10 12:08

hersh


People also ask

How do you store a JSON in a hidden field?

just set the hidden field with javascript : document. getElementById('elementId').

How do you store a value in a hidden field?

In jQuery to set a hidden field value, we use . val() method. The jQuery . val() method is used to get or set the values of form elements such as input, select, textarea.

How do you store hidden value in HTML?

The <input type="hidden"> defines a hidden input field. A hidden field let web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.


2 Answers

Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...

Here I'll explain what I mean:

<input type="hidden" value="{"name":"John"}"> 

As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:

<input type="hidden" value="{" rubbish > 

So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:

> encodeURIComponent(JSON.stringify({"name":"John"})) > "%7B%22name%22%3A%22John%22%7D" 

Now that value can be safely stored in an input hidden type like so:

<input type="hidden" value="%7B%22name%22%3A%22John%22%7D"> 

or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:

<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div> 

Now to read the data back we can do something like:

> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json"))) > console.log(data) > Object {name: "John"} 
like image 91
rodu Avatar answered Sep 20 '22 18:09

rodu


You can use input.value = JSON.stringify(obj) to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)

The JSON object is available on modern browsers or you can use the json2.js library from json.org

like image 37
Mic Avatar answered Sep 21 '22 18:09

Mic