stackyyflow stackyyflow - 1 month ago 14
HTML Question

Bootstrap select custom dynamic options

I am using bootstrap select and I encounter a problem when I want to add dynamic options using Javascript. The list is always empty. When I switch back to using HTML select the following Javascript code works perfectly.

HTML:

<select class="selectpicker" data-style="btn-lg btn-list-author"
id="author-list" data-live-search="true" title="Select Author"></select>


Javascript:

readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text){
data = JSON.parse(text);
$.each(data, function(i, v) {
alert(v.login);
var ul = document.getElementById("author-list");
var li = document.createElement("option");
var linkText = document.createTextNode(v.login);
li.appendChild(linkText);
ul.appendChild(li);
})
});

Answer

With bootstrap-select you need to call the refresh method of the select-picker after you add new options.

Excerpt from bootstrap-select refresh Documentation:

.selectpicker('refresh')

To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.

Untested Example Using Your Original Code:

readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
    data = JSON.parse(text);
    $.each(data, function(i, v) {
        alert(v.login);
        var ul = document.getElementById("author-list");
        var li = document.createElement("option");
        var linkText = document.createTextNode(v.login);
        li.appendChild(linkText);
        ul.appendChild(li);
    })

    // Example call of 'refresh'
    $('.selectpicker').selectpicker('refresh');
});

This lets bootstrap-select know of the data changes to the select element so it can redraw it's contents.

Working Example (with a modified version of your code)

Working Codepen with some modifications

Codepen Code:

// Had to create some stubs to replace missing code.
var repolink = 'silviomoreto/bootstrap-select';

function readDataFromGit (url, callback) {
  $.get(url, callback);
}
//End of stubs


  readDataFromGit('https://api.github.com/repos/' + repolink + '/contributors', function(text) {
      data = text; // Changed this because my stub is already returning parsed JSON.
      var ul = document.getElementById("author-list"); // moved this out of the loop for a bit of performance improvement (not relevant to the solution.)

      $.each(data, function(i, v) {
          var li = document.createElement("option");
          var linkText = document.createTextNode(v.login);
          li.appendChild(linkText);
          ul.appendChild(li);
      })

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