I'm trying to implement bootstrap-select
in my application. I already use Bootstrap-twitter in my application. There are few drop-down menus in the system where I would like to implement this feature. On page load bootstrap-select will be triggered and drop down menu is populated from json file. I have form int he system where JSON file can be updated. In that case I reload JSON file and call function to load the json again. The problem is that bootstrap-select breaks in that case. I still can click and search through the options but at the same time all options are showing below the select input field. Here is example of my code:
var appData = {
Buildings : [
{BLDGNAME : "Test 1", BLDGNUMBER : "2234"},
{BLDGNAME : "Test 2", BLDGNUMBER : "2534"},
{BLDGNAME : "Test 3", BLDGNUMBER : "2734"},
{BLDGNAME : "Test 4", BLDGNUMBER : "2294"}
]
}
$(document).ready(function(){
loadBuildings();
});
function loadBuildings(){
populateBuildings();
/* Just to show the way I import JSON data.
$.getJSON("JSON/Buildings.json?"+ new Date().getTime(), function(json) {
appData.Buildings = json;
}).done(function() {
populateBuildings();
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log( "Error: " + errorThrown);
});
*/
}
function populateBuildings(){
var fldBldg = $(".bldg-menu");
fldBldg.find("option:gt(0)").remove(); // Remove all but the first option in select menu.
$.each(appData.Buildings, function (key, value) {
fldBldg.append($("<option></option>").val(value.BLDGNUMBER).text(value.BLDGNAME));
});
fldBldg.selectpicker("refresh");
}
$("#add").on("click",addNew);
function addNew(){
appData.Buildings.push({BLDGNAME : "Test 5", BLDGNUMBER : "6234"});
loadBuildings();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<form name="frmDemog" id="frmDemo">
<div class="form-group">
<label class="control-label" for="bldg"><span class="label label-primary">Building:</span></label>
<select class="form-control bldg-menu selectpicker" name="frmDemo_bldg" id="frmDemo_bldg" data-live-search="true" required>
<option value="">--Choose Building--</option>
</select>
</div>
</form>
<button type="button" name="add" id="add">Add New</button>
If you run snippet above and click on the add button you will see all options below the select menu. I'm not sure how I can reload the selectpicker()
to prevent that behavior. I have tried using selectpicker("refresh")
but that did not help. If anyone knows the way to fix this please let me know. Thank you.