17

I have an input field like the one below

 <input type="hidden" value="" id="inputField">

Now I have list of products and for each product I have a checkbox. When a user clicks on the checkbox, I get the product id and name. Now I want to save it again in the hidden field like below

<input type="hidden" 
       value="[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]"
       id="inputField"
>

My first question is how I can do this and how can I create the JSON?

Secondly if the user again unchecks a product checkbox then I need to get the current hidden value and convert it into some data structure, remove the unchecked box id from the data structure and then save it again in the hidden field.

Is there any library which does this job in JavaScript?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user882196
  • 1,691
  • 9
  • 24
  • 39
  • I am a bit confused as to what you are trying to accomplish. What is being stored in the value of the hidden field? The input name and ID? – Norman Joyner Aug 17 '11 at 17:34
  • @norman : [{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}] – user882196 Aug 17 '11 at 17:35
  • So it is the input name and ID from the checkbox input element? – Norman Joyner Aug 17 '11 at 17:36
  • 2
    It seems to me you have asked [this question already](http://stackoverflow.com/questions/7086208/how-i-can-store-javascript-array-object-saved-somehow-so-that-i-can-use-it-later) and the the answer you accepted covers everything you asked here. – Felix Kling Aug 17 '11 at 17:55
  • No its the product name and id...it has got nothing to do with check id and name. – user882196 Aug 17 '11 at 18:01
  • So where are the product id and name located, you will have to explain this in more detail in order for someone to give you an appropriate answer. – Norman Joyner Aug 17 '11 at 18:03
  • 1
    The question seem similar enough to transfer the knowledge from the first one to the second one. If they are not similar you have to provide a better explanation of your problem. In any case, I think it would help you to read about some basics. Have a look at [this JavaScript guide](https://developer.mozilla.org/en/JavaScript/Guide). – Felix Kling Aug 17 '11 at 18:13
  • Use single quotes as suggested below in one of the answers from Diodeus – Gurucharan Balakuntla Maheshku Apr 19 '16 at 03:46

8 Answers8

7

Using jQuery:

HTML:

<input type="hidden" value='[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]'
 id="inputField">

JS:

var data = {}
data.products = jQuery.parseJSON($('#inputField').val())
alert(data.products[0].product_id) 
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
4

The building block that you look for are JSON.stringify and JSON.parse;

var stringData = '[{"product_id":123,"name":"stack"}, {"product_id":456,"name":"overflow"}]';
// Convert a string to an JavaScript object
var arrayData = JSON.parse(stringData);
// Convert a JavaScript object to a string
stringData = JSON.stringify(arrayData);

Now, whenever one of your checkboxes changes state, you'd get the object from the hidden field and modify it. After the modification of the object, you'd save the string back to the hidden field.

To read and store the value from/to the hidden field:

var field = document.getElementById('inputField');
// Reading the value
stringData = field.getAttribute('value');
// Storing the value
field.setAttribute('value', stringData);

You still lack the modifications of your array which you would do similar to:

// Adding a newly checked product
arrayData.push({
    product_id: …,
    name: …
});

// Removing a product from the list is more complicated
arrayData = arrayData.filter(function(product){
    var productIdToRemove = …;
    return product.product_id!==productIdToRemove;
});

Regarding libraries: Probably most do contain code to facilitate array manipulation and setting of form data. See the documentation of jQuery or prototype or the other answers for examples.

Just a thought: Wouldn't it be simpler to discard the whole idea of using the hidden field and transfer the checkboxes to the server instead. If the checkbox was checked, use it, otherwise ignore the correlating product data.

Augustus Kling
  • 3,303
  • 1
  • 22
  • 25
  • is "adding a newly checked product" code workabale or it's just u wanted to show me...and also with "Removing a product"... – user882196 Aug 17 '11 at 18:06
  • actually when the user check some checkboxes he remians on the page. Then there is one more button which on clicking displa what the user have selected. So i need to hidden field to keep a track of user selected products. – user882196 Aug 17 '11 at 18:11
  • 3
    Everything presented in the answer are building blocks that show how to do stuff. It's not intended to be copied and pasted to have a running version. You need to add event handlers to the checkboxes yourself and use the conversions wherever your final code needs them. Copy-and-Past-ready code is not possible with the information provided in the question nor do I think it would help you in the long-term. If you do intent to use the hidden field only on the client, you could yourself save the trouble and use a simple variable instead that persists over the execution of the event handlers. – Augustus Kling Aug 17 '11 at 18:17
3

In JavaScript, just assign the value:

var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);

In a server-side language, encode the JSON in HTML, for example with php's htmlspecialchars or python's html.escape. The result will look like this:

<input type="hidden" id="inputField"
       value="[{&quot;product_id&quot;:123,&quot;name&quot;:&quot;stack&quot;}]">
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I know this stringify already but how i can create this object – user882196 Aug 17 '11 at 17:37
  • [{"product_id":123,"name":"stack"}] – user882196 Aug 17 '11 at 17:37
  • and when new products are added how can i update this objects,,, – user882196 Aug 17 '11 at 17:38
  • @user882196 Depends on where you're getting the data for the object from. If its separate form field, something like: `var data = [{product_id: document.getElementById("product_id0").getAttribute("value"), name: document.getElementById("name0").getAttribute("value")}];`. Better ask a new question about how to create the array, since that subproblem is not related to JSON at all. – phihag Aug 17 '11 at 17:40
  • i never said a word about JSON in my question....so probably i don't need to create another issue. – user882196 Aug 17 '11 at 18:07
2

As it is stated in other answers below, to convert JSON to string, use JSON.stringify() function like so:

var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);

And you get string representation of JSON object in var json. To do this other way round so you can update the actual JSON object contained in that string, you can use eval:

var json_object = eval("("+json+")");

Now, original JSON object is recreated, and you can update it, and re-strigify it back to hidden field or some other var...

Cipi
  • 11,055
  • 9
  • 47
  • 60
  • 7
    NEVER use `eval()` in javascript. Use JSON.parse() (and pay attention not to pass it a null). – Adrien May 30 '14 at 16:21
1

I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we should have something like the following:

var data= "{"name":"John"}";

var encodeddata encodeURIComponent(JSON.stringify(var data= "{"name":"John"}";
))

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

<input type="hidden" value="'+encodeddata+'">

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

var data = JSON.parse(decodeURIComponent(value))
Tom
  • 4,257
  • 6
  • 33
  • 49
SHIBIN
  • 397
  • 3
  • 5
1

I am still a bit confused about your question, but if you are simply storing the name and id from the input checkboxes which are checked you can do this quite simply using jQuery.

var jsonArray = [];
$("input:checkbox:checked").each(function(){
    var jsonObj = {};
    jsonObj.product_id = $(this).attr("id");
    jsonObj.name = $(this).attr("name");
    jsonArray.push(jsonObj);
});

The variable jsonArray will now hold a json string similar to the example you have posted. You can use JSON.stringify(jsonArray) to see this.

There is no need to create the hidden field, holding this string as the value and trying to add and remove from it as checkbox states change. Simply execute the javascript when the page is ready to change via button click, etc.

Best of luck.

Norman Joyner
  • 955
  • 6
  • 12
  • actually in the webpage with each product i have a checkbox .So when the user clicks on the checkbox i sent the productID and productName to a javascript function which then do all the processing and then save the final list to the hidden field. This productID and ProductName is not the checkbox id and Checkbox name. – user882196 Aug 17 '11 at 18:04
  • This solution assumes that the product name and id were set in the checkbox name and id. If this is not the case it will not work. You can change where jsonObj.product_id and jsonObj.name get their value. – Norman Joyner Aug 17 '11 at 18:18
0

If you have a JSON object, save it to the hidden field using JSON.stringify:

var myObj = [{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}];
document.getElementById('inputField').value = JSON.stringify(myObj);
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
-1

Add library

"<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>"

Use: ${fn:escapeXml(string1)}

input type="hidden" value="${fn:escapeXml(string1)}" id="inputField"