Populate a jQuery Dropdown From AJAX
From Logic Wiki
HTML
<select id="dropdown"></select>
Data
[
{"id":1,"name":"Option 1"},
{"id":2,"name":"Option 2"},
{"id":3,"name":"Option 3"},
{"id":4,"name":"Option 4"},
{"id":5,"name":"Option 5"},
]
AJAX
$.ajax({
type: "POST",
url: urlPath,
success: function(data)
{
helpers.buildDropdown(
jQuery.parseJSON(data),
$('#dropdown'),
'Select an option'
);
}
});
var helpers =
{
buildDropdown: function(result, dropdown, emptyMessage)
{
// Remove current options
dropdown.html('');
// Add the empty option with the empty message
dropdown.append('<option value="">' + emptyMessage + '</option>');
// Check result isnt empty
if(result != '')
{
// Loop through each of the results and append the option to the dropdown
$.each(result, function(k, v) {
dropdown.append('<option value="' + v.id + '">' + v.name + '</option>');
});
}
}
}