最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bootstrap select custom dynamic options - Stack Overflow

programmeradmin1浏览0评论

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

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);
     })
});
Share Improve this question asked Oct 30, 2016 at 18:27 stackyyflowstackyyflow 7633 gold badges14 silver badges31 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 13

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

Here is a dynamic drop-down menu with grouped options from a data array:

// Example data Array list
namespace_list = [
    ['test1-c1', 'test2-c1', 'test3-c1', 'test4-c1', 'test5-c1', 'test6-c1'],
    ['test1-c2', 'test2-c2', 'test3-c2', 'test4-c2', 'test5-c2', 'test6-c2']
]


$('#pod_dropdown').selectpicker();

// Selecting selectpicker dropdown
select = document.getElementById('pod_dropdown');

for (let namespace of namespace_list) {

    // Generating group name
    namespace_name = namespace[0].slice(6, 8)+'-title'

    // Creating the optiongroup

    var optgroup = document.createElement('optgroup');
    optgroup.id = namespace_name;
    optgroup.label = namespace_name
    // Appending optiongroup to the dropdown
    select.appendChild(optgroup);

    // Selecting the optiongroup 
    optiongroup = document.getElementById(namespace_name);

    for (let pod of namespace) {

        // Creating the options of the optiongroup 
        var opt = document.createElement('option');
        opt.value = pod;
        opt.innerHTML = pod;
        // Appending the option to the optiongroup
        optiongroup.appendChild(opt);

    }

}
// Refresh the dropdwon menu
$('#pod_dropdown').selectpicker("refresh");



// Getting the value after selecting it in the UI and unselect the dropdown

function filterpod() {
    let pod = $('#pod_dropdown').val().toString();
    console.log(pod)

}
    <!-- jquery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- bootstrap -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- multi select dropdown -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

    <!-- Creatting the dropdown -->
    <select id="pod_dropdown" class="selectpicker" data-style="btn btn-primary btn-sm" multiple data-live-search="true" data-width="auto"></select>
    
    <!-- Calling the function filterpod when hide dropdown after select option -->
    <script type="text/javascript">
        $('#pod_dropdown').on('hide.bs.select', function(e) {filterpod();});
    </script>

发布评论

评论列表(0)

  1. 暂无评论