Reputation: 1721
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?
Upvotes: 17
Views: 59133
Reputation: 467
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))
Upvotes: 1
Reputation: 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"
Upvotes: -1
Reputation: 3333
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.
Upvotes: 5
Reputation: 955
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.
Upvotes: 1
Reputation: 11343
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...
Upvotes: 2
Reputation: 114367
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)
Upvotes: 7
Reputation: 23142
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);
Upvotes: 0
Reputation: 287835
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="[{"product_id":123,"name":"stack"}]">
Upvotes: 3