Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  196] [ 6]  / answers: 1 / hits: 28475  / 11 Years ago, tue, december 10, 2013, 12:00:00

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!


More From » jquery

 Answers
10

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.


[#73816] Monday, December 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenamackennac

Total Points: 304
Total Questions: 110
Total Answers: 107

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;