So, here\'s the deal: I have a JSON object saved in my web App at localStorage.
This JSON is being saved as a string, with JSON.stringify
, inside one of my function
to answer the actual question on how to do this in json2html .. with the correct transform
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'${CODE}',html:'${NAMEVAR}'};
document.getElementById('mySelectID').innerHtml = json2html.transform(jsonData,transform);
OR using the jquery plugin for json2html
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'${CODE}',html:'${NAMEVAR}'};
$('#mySelectID').json2html(jsonData,transform);
You don't need the transform for this, try it this way:
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var $select = $('#mySelectID');
$(jsonData).each(function (index, o) {
var $option = $("<option/>").attr("value", o.CODE).text(o.NAMEVAR);
$select.append($option);
});
Here is a working fiddle.
$.ajax({
url:'test.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
most immediately you need to change this:
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'.CODE',html:'{$NAMEVAR}'};
To this:
var jsonData = $.parseJSON(window.localStorage.getItem("MyData"));
var transform = {tag:'option', id:'{$CODE}',html:'{$NAMEVAR}'};
That's just a key to get to the data, so make sure you use the same key.
There may be some difficulty in rendering:
value="1"
As you are depending id="{$CODE}" to translate to that, which it will not do automatically.
Good luck!
As you are starting you can learn more of JavaScript from w3schools. There is an DOM object called Element that you can use to add an option into select. You just need to do something like:
var el = document.getElementById('mySelectID'); //Get the select element
var opt = document.createElement('option'); //Create option element
opt.innerHTML = "it works!"; //Add a value to the option
el.appendChild(opt); //Add the option to the select element
I think there are a couple of errors in your code. Try this instead:
// it's class, not id, and no fullstop required.
// The $ sign was in the wrong place.
var transform = {tag:'option', class:'$(CODE)', html:'${NAMEVAR}'};
// it's innerHTML not innerHtml
document.getElementById('mySelectID').innerHTML = json2html.transform(jsonData, transform);