Reputation: 513
I have the following multiple select field from Bootstrap 3 framework:
<select class="selectpicker" multiple name="regions" id="regions">
<option value="99">All regions</option>
<option value="AC">AC</option>
<option value="AL">AL</option>
<option value="AP">AP</option>
</select>
And its jQuery code:
$("#regions").change(function(){
if($("option:selected:last",this).val() == 99){
$('#regions option').prop('selected', true);
} else{
$('#regions option').prop('selected', false);
}
});
The issue is: when the "All regions" option is selected, the multiple select is not updated with all the options selected.
Upvotes: 3
Views: 16765
Reputation: 1546
Im not sure what you exactly trying to achieve, if I get it correct you want to select all if user selects the first one with the value=99
and select individuals if they select others right?
$("#regions").change(function(){
var selectedValue = $("option:selected", this).val();
if(selectedValue == 99){
$('option', this).prop('selected', true);
} else{
$(this).prop('selected', true);
$(this).siblings().prop('selected', true);
}
});
See the example: https://jsfiddle.net/pwdu8wab/4/
Upvotes: 0
Reputation: 331
If you are using the bootstrap-select component, two options:
1. Built in
Add
data-actions-box="true"
to your select tag in html.
If you need custom labels:
$.fn.selectpicker.defaults = {
selectAllText: "All",
deselectAllText: "None"
}
2. Manually
You can select/deselect all options in html select and refresh the bootstrap-select component:
$("#your-select option").attr("selected", *value)
$("#your-select").selectpicker("refresh") // must be already initialized
*value = true | "selected" | false | null
Note: in my tests using bootstrap-select and this approach, i could only deselect all. When i tried to select all, the component was not updated.
https://github.com/silviomoreto/bootstrap-select/issues/825
Upvotes: 1