Bootstrap-select: Ajax/JSON data source support

Created on 29 Jan 2015  路  15Comments  路  Source: snapappointments/bootstrap-select

Can You add option to load options in ajax?

enhancement

Most helpful comment

+1 for official support for Ajax loading!

All 15 comments

@piernik I built a plugin just for this. It goes on top of bootstrap select and should be able to do everything you want. If you use it and you have any questions/concerns/bugs make an issue on that repo.

Or for a simple usecase you can extend it yourself. Note that this basicly switches local search to ajax search, and will not play nice if there are multiple values returned with ajax.

        var responseToSelect = function (data, selectBox) { // convert ajax response ...
            if (data.length > 0) {
                var output = [];
                $.each(data, function (i, dat) {
                    output.push("<option value=\"" + dat.Value + "\">" + dat.Text + "</option>");
                }); // ... into options ...
                selectBox.html(output.join("")); // ... on the original element
                selectBox.selectpicker("refresh"); // refresh the options
            }
        }
        var inp = "";
        $(".autocomplete")
            .each(function () {
                var thi$ = $(this); // hold on to the original element
                thi$.selectpicker({
                    liveSearch: true
                }); // turn it into a bootstrap select with search field
                thi$.next().on("input", function (evt) { // listen on the created elements for input
                    var $earch = $(evt.target); // hold on to the search input field
                    if ($earch.val() !== inp) { // if the search value is changed
                        inp = $earch.val();
                        if (inp.length > 2) { // and it has 3 or more characters ...
                            var url = thi$.data("completeurl") + "/"; // get an url to ...
                            $.get(url, { code: "", search: inp }) // do an ajax call to get more countries
                                .done(function (data) { responseToSelect(data, thi$) });
                        }
                    }
                });
            });

+1 for official support for Ajax loading!

Agreed! Official support would be fantastic. Select2 is superior in this regard (but not in many others). I tried ajax-bootstrap-select but it is bloated and buggy, nowhere near the quality of bootstrap-select itself.

+1 for official support for Ajax loading! # #

+1 and bump

+1 and another bump..

Any progress on this?

+1 and bump!

First steps taken to support this. It's now possible to load in the the select options using the data property:

$('#test').selectpicker({
  data: [
    {
        text: 'Bread'
    },
    // optgroup
    {
      text: 'Picnic',
      icon: 'fa-home',
      children: [
        {
          text: 'Mustard',
          value: 'mustard',
          selected: true
        },
        {
          text: 'Ketchup',
          value: 'ketchup'
        },
        {
          text: 'Relish',
          value: 'relish'
        }
      ]
    }
  ]
});
$('#test2').selectpicker({
  data: function (callback) {
    var array = [
      {
        text: 'Tent',
        icon: 'fa-camera'
      },
      {
        text: 'Flashlight',
        selected: true
      },
      {
        text: 'Disabled Option',
        disabled: true
      },
      {
        value: 'divider',
        divider: true
      },
      {
        text: 'Toilet Paper'
      }
    ];

    callback(array);
  }
});

See an example here: https://plnkr.co/edit/NXB03TGwGPsD7BSj. This feature required a lot of rewiring under the hood, so it will require additional bug testing. I'll probably have to release a v1.14.0-beta first.

Still todo:

  • [ ] Support using a different data source when searching
  • [ ] Pull in new or updated data when scrolling (includes pagination support)

Edit:

Found a bug: for multiple selects, calling refresh() resets the select back to its initial state (so any new selected options are reverted). Thinking we'll have to change the API so the default selected status of options is set separately.

if anyone tired of waiting, I came up with a solution that is working pretty well for me. I havent tested much but so far so good.

const axios = require('axios');

module.exports = (selector, url) => {
    const $select= $(selector).selectpicker({
        noneSelectedText: 'Ambassador Search'
    });

    const $input = $select.parent().find('input[type=search]');

    $input
        .on('input', (e) => {
            const value = e.target.value;

            if (value.length < 3) {
                return;
            }

            axios.get(`${url}?search=${value}`)
                .then(({data: results} = []) => {
                    $select.empty();

                    results.forEach((result) => {
                        $(`<option value="${result.discord_user_id}">${result.discord_username} | ${result.discord_nickname}</option>`).appendTo($select);
                    });

                    $select.selectpicker('refresh');
                });
        });
}

Released in v1.14.0-beta!

Can you give an example on how remote data loading can tie into the new data property?

@chase439 See https://github.com/snapappointments/bootstrap-select/releases/tag/v1.14.0-beta for some examples.

$('#test2').selectpicker({
    source: {
        data: function (callback) {
            $.ajax('/api/load-options')
                .then((response) => callback(response.data))
        }
    }
});

This issue can be unpinned now that it is closed.

Was this page helpful?
0 / 5 - 0 ratings