Insert into HTML select tag options from a JSON

Malavos picture Malavos · Dec 10, 2013 · Viewed 27.4k times · Source

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 functions, on the page load:

localStorage.setItem("MyData", JSON.stringify(data));

data is being saved like this:

[{"NAMEVAR":"Some Data 1","CODE":"1"},{"NAMEVAR":"Some Data 2","CODE":"2"}]

data is the result from a request. The data is being saved successfully at the home page, so i could use later. After that, i have to load up a form on another page, using what i got from data.

I have this select tag on the page:

<select id="mySelectID" name="select" class="main-form">
<option value="">None Selected</option>
</select>

What i want to do is simple: I'm using json2html to add items to this select tag from the data, and the option value has the CODE from data. So, what i expected to happen is:

<select id="mySelectID" name="select" class="main-form">
<option value="1">Some Data 1</option>
<option value="2">Some Data 2</option>
</select>

by doing this:

var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var transform = {tag:'option', id:'.CODE',html:'{$NAMEVAR}'};
document.getElementById('mySelectID').innerHtml = json2html.transform(jsonData,transform);

But this does not work, and i know it won't. The problem is that i do not know how to insert this JSON into options to my HTML. I thought that json2html could help me, but as i do not speak English natively, it's kinda of being hard for me to understand that, and I'm also new to JavaScript.

Thanks!

Answer

Esko picture Esko · Dec 10, 2013

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.