I am trying to change the options of a second dropdown list based on the selection of the first dropdown.
The code it works as you can see here. However because it does not work since I make use bootstrap-select.js. The reason that I added this is to have a nice multiple effect selection.
Apparently, the reason is because it is not anymore a simple <select>
with <option>
after the JS, but I do not know how to find a solution on this.
This is the code
<select class="form-control" id="choice1">
<option value="Food">Food</option>
<option value="Fruit">Fruit</option>
</select>
<select class="selectpicker" multiple id="choice2">
<option data-option="Food" value="M">Mustard</option>
<option data-option="Food" value="M">Ketchup</option>
<option data-option="Fruit" value="M">Apple</option>
<option data-option="Fruit" value="M">Orange</option>
</select>
$("#choice1").change(function() {
if(typeof $(this).data('options') === "undefined") {
$(this).data('options',$('#choice2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-option=' + id + ']');
$('#choice2').html(options);
});
Bootstrap-select.js has a refresh
method you can use. Your JS code will be like:
$("#choice1").change(function () {
if (typeof $(this).data('options') === "undefined") {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#choice2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-option=' + id + ']');
$('#choice2').html(options);
//Refresh #choice2 to show the new values
$('#choice2').selectpicker('refresh');
});
Here is a working demo.