Bootstrap-select: Load from JSON

Created on 13 Sep 2015  路  4Comments  路  Source: snapappointments/bootstrap-select

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');
        });
    });
});

Most helpful comment

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');
}

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

M1chae1 picture M1chae1  路  3Comments

bhritch picture bhritch  路  3Comments

Cruyjun picture Cruyjun  路  3Comments

anton164 picture anton164  路  4Comments

Godrules500 picture Godrules500  路  4Comments