Jackson Sentzke Jackson Sentzke - 1 month ago 8
JSON Question

JQuery: Populate HTML dropdown menu with JSON

I know this questions been asked before, I've read other posts and couldn't get it to work.

I'm trying to populate a drop down menu with JSON data but I'm having some issues, the drop down appears on my html page but theres nothing in the drop down, not even the "Please Select". Below is my code, do you see any problems with it.

HTML

<select id="dropDown">
</select>


JavaScript

$(document).ready(function () {
$.ajax({
url: 'http://localhost/api/Dynamic?database=',
dataType: 'Json',
success: function (results) {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
}
});
});


JSON

["Item1","Item2","Item3","Item4"]

Answer

Have you included jquery in your html head tag
Please also check your ajax is returning json data
I have make a fiddle and its working fine for me

$(document).ready(function() {
 var $el = $("#dropDown");
var results = ["Item1","Item2","Item3","Item4"];
            $el.empty(); // remove old options
            $el.append($("<option></option>")
                    .attr("value", '').text('Please Select'));
            $.each(results, function (index, value) {
                $el.append($("<option></option>")
                        .attr("value", value).text(value));
            });
});

Here is working jsfiddle
https://jsfiddle.net/o5ju4kja/

Comments