bootstrap-select nothing selected

Sanzeeb Aryal picture Sanzeeb Aryal · Aug 4, 2016 · Viewed 15k times · Source

I am using bootstrap select.

<select name="categories[]" id="cat" class="selectpicker" multiple>
</select>

and getting the option tag from here,

var result='';
for(var i=0;  i<res.getcategories.length;  i++) 
{                    
  result += '<option value='+res.getcategories[i].cat_id+'>'+res.getcategories[i].category+'</option>';                 
   $('#cat').html(result); 

}

However it always displays Nothing selected and i donot display other options. If i donot use bootstap class 'selectpicker' everything is fine.

Answer

gaetanoM picture gaetanoM · Aug 7, 2016

Whenever you add or remove elements from a selectpicker you need:

.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.

This means you have to execute:

$('#cat').selectpicker('refresh');

When you need to add on the fly a new element the clearest and simplest way is to use jQuery:

$('#cat').append($('<option>', {
    value: res.getcategories[i].cat_id,
    text: res.getcategories[i].category
}));

In this way you avoid problems with < and > or " and ' symbols and whatnot.

In order to handle the selections you can use changed.bs.select.

So, an example on how to add on document ready and whenever you click the add button and the corresponding implementation of remove and selection is:

var res = {
  getcategories: [{cat_id: 'Cat Id 1', category: 'Category 1'},
                  {cat_id: 'Cat Id 2', category: 'Category 2'}, {cat_id: 'Cat Id 3', category: 'Category 3'},
                  {cat_id: 'Cat Id 4', category: 'Category 4'}, {cat_id: 'Cat Id 5', category: 'Category 5'}]
};

$(function () {
  $('#add').on('click', function (e) {
    for (var i = 0; i < res.getcategories.length; i++) {
      $('#cat').append($('<option>', {
        value: res.getcategories[i].cat_id,
        text: res.getcategories[i].category
      }));
    }
    $('#cat').selectpicker('refresh');
  }).trigger('click');  // this line to load on selectpicker on document ready

  $('#remove').on('click', function (e) {
    $('#cat option').remove();
    $('#cat').selectpicker('refresh')
  });
  
    $('#cat').on('changed.bs.select', function(e) {
      console.log('Selected elements: ' + ($('#cat').val() || ['Nothing selected']).join(', '));
    })
});
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>


<div class="container">
    <h1>Selectpicker</h1>

    <div class="row">
        <div class="col-xs-12">
            <select name="categories[]" id="cat" class="selectpicker" multiple>
            </select>
        </div>
    </div>
</div>
<div class="container-fluid">
    <h1></h1>

    <div class="row">
        <div class="col-xs-4">
            <button id="add" type="button" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-plus"></span>
                Add Options
            </button>
        </div>
        <div class="col-xs-8">
            <button id="remove" type="button" class="btn btn-default btn-lg"><span
                    class="glyphicon glyphicon-remove"></span> Remove Options
            </button>
        </div>
    </div>
</div>