Reputation: 55
I have a bootstrap Selectpicker controle, I want to fill it with Javascript, the code works fine with simple Select input, but when I add class="selectpicker"
it doesn't work anymore
Here is my code : HTML
<select id="hotspotList" class="selectpicker show-menu-arrow form-control">
</select>
Javascript
var select = document.getElementById("hotspotList");
var options = ["1", "2", "3", "4", "12"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
Upvotes: 1
Views: 3122
Reputation: 6992
$('.selectpicker').selectpicker('refresh');
will work.
function addMore(){
var select = document.getElementById("hotspotList");
var options = ["1", "2", "3", "4", "12"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
$(".selectpicker").selectpicker('refresh');
}
$(document).ready(function(){
$(".selectpicker").selectpicker();
})
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/css/bootstrap-select.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/js/bootstrap-select.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<select class="selectpicker" id="hotspotList">
<option>Mustard</option>
<option>Ketchup</option>
<option>Barbecue</option>
</select>
<button onclick="addMore()"> addMore !</button>
Upvotes: 0
Reputation: 2536
Updated:
Just Enable Bootstrap - Select via JavaScript like:
$('#hotspotList').selectpicker('refresh');
Upvotes: 0
Reputation: 36609
Use
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. Refer https://silviomoreto.github.io/bootstrap-select/
$('.selectpicker').selectpicker('refresh');
Upvotes: 3