Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery fill DropDownList with JSON data

Let's say I have this data returned from a backend service layer:

["2", "3", "7", "14"]

First question. Is this considered valid JSON data? Json.org says it is, but I cannot find any references to it on Google, SO, etc...

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

I want to be able to take these values and add them to an already existing DropDownList object OnLoad using JQuery.

$.getJSON("http://www.example.com/path-to-get-data", function(data) { 
  //iterate through each object and add it to the list.
  //ideally, the key and value (string to display to the end user) would be the same.
});

I took a look at this thread, but it has objects, not just an array. Should I use parseJSON versus getJSON?

Thanks in advance!

like image 677
Mr. C Avatar asked Sep 28 '13 03:09

Mr. C


Video Answer


1 Answers

var arr = [ 2, 3, 7, 14];
$.each(arr, function(index, value) {
     ('#myselect').append($('<option>').text(value).attr('value', index));
});

Please also take a look at Mr. C's solution:

$('<option></option>').val(item).html(item)

His way of manipulating options is new to me, and more elegant.

like image 79
Blaise Avatar answered Sep 28 '22 08:09

Blaise