tags:

views:

79

answers:

2

Hi all, this is my JSON data:

{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria"}

How to display this JSON data in a selectlist?

+5  A: 

Use $.each and iterate over all your elements. This should work:

$.each(jsonData, function(key, value)
{
   $('<option></option>').val(key).text(value).appendTo('#yourSelectList');
});
alexn
Depending on the size of the data, many .append() operations can be expensive. It's much faster to create a placeholder array, and .push() each option onto it, then .append(myArray.join('')) only once.
MightyE
This is wrong. What the heck is `this.code` and `this.name`? It doesn't work at all. Have no idea why this is getting up-voted.
patrick dw
MightyE: that would only make any sense if we were talking about HTML strings. (And even then, jQuery's `append` function still has to append each DOM Node one-by-one, so you don't save anything by doing it like that.)
bobince
@patrick You're completely right. Got a little to fast. Updated my answer.
alexn
+1 for the corrections.
patrick dw
+1  A: 

Here's one way (takes fewer function calls):

var myJson = {"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria"};

$.each(myJson,function(key,val) {
    $('#mySelect').append('<option value="'+ key + '">' + val + '</option>');
});
patrick dw
bobince
@bobince - I see what you mean. Does calling `.val()` and `.text()` a sufficient avoidance of that issue?
patrick dw
Yep. And `.attr()` for other cases.
bobince