I need to load my lists from JSON files so I have made an extension to your script. Rather than modifying it I chose to extend it in order to keep it simple to receive your updates. Everyone are welcome to use my extension, but I hope it will be implemented in the codebase.
It works like this:
Add an attribute to your select: data-url="link-to-json", make sure the select has the class selectpicker.
The json file must be formatted like this:
[{
name: "Name",
id: 1
},
{
name: "Name2",
id: 2
}]
And so on. It will take name as display value and id as option value.
$(document).ready(function()
{
$('select[class~="selectpicker"][data-url]').each(function(index, value)
{
var select = $(this);
var url = $(this).attr('data-url');
var list = [];
$.getJSON(url, function(data)
{
$.each(data, function(key, val)
{
list.push('<option value="' + val.id + '">' + val.name + '</option>');
});
select.html(list.join(''));
select.selectpicker('refresh');
});
});
});
An updated version which allows you to define the value and label as attributes
data-id="value"
data-label="label"
$( document ).ready(function()
{
$('select[class~="selectpicker"][data-url]').each(function(index, value)
{
var select = $(this);
var url = $(this).attr('data-url');
var id = $(this).attr('data-id');
var label = $(this).attr('data-label');
$.getJSON(url, function(data)
{
select.html('');
$.each(data, function(key, val)
{
select.append('<option value="' + val[id] + '">' + val[label] + '</option>');
});
select.selectpicker('refresh');
});
});
});
another option to load/reload data from a json item list
function loadSelectItems(select, items) {
var options = '';
$.each(items, function(key, value) {
options += '<option value=' + key + '>' + value + '</option>';
});
select.empty();
select.append(options);
select.selectpicker('refresh');
}
Please 馃憤 and follow #899.
Most helpful comment
another option to load/reload data from a json item list