Reputation: 925
I would like to prevent users to remove pre-selected options in my Chosen dropdown (multiple).
<select data-placeholder="Your Favorite Types of Bear" multiple class="chosen-select" tabindex="8">
<option value=""></option>
<option>American Black Bear</option>
<option>Asiatic Black Bear</option>
<option>Brown Bear</option>
<option>Giant Panda</option>
<option selected>Sloth Bear</option>
<option selected>Sun Bear</option>
<option selected>Polar Bear</option>
<option selected>Spectacled Bear</option>
</select>
So I want the Sloth Bear, Sun Bear, Polar Bear and Spectacled Bear selected, and the user can't remove it. How do I go about that?
Upvotes: 0
Views: 908
Reputation: 176
As of my knowledge, there is no perfect way for that. But as a workaround, you can try to disable the options you want to prevent so that they cannot modify their visibility.
You can try the below code:
<select data-placeholder="Your Favorite Types of Bear" multiple class="chosen-select" tabindex="8">
<option value=""></option>
<option>American Black Bear</option>
<option>Asiatic Black Bear</option>
<option>Brown Bear</option>
<option>Giant Panda</option>
<option disabled>Sloth Bear</option>
<option disabled>Sun Bear</option>
<option disabled>Polar Bear</option>
<option disabled>Spectacled Bear</option>
</select>
Upvotes: 0
Reputation: 4923
I think there is no official way to do this.
But let me give you an idea.
Define your select
items like this.
<select data-placeholder="Your Favorite Types of Bear" multiple class="my_select_box" tabindex="8">
<option value=""></option>
<option value="1">American Black Bear</option>
<option value="2">Asiatic Black Bear</option>
<option value="3">Brown Bear</option>
<option value="4">Giant Panda</option>
<option value="5" disabled selected>Sloth Bear</option>
<option value="6" disabled selected>Sun Bear</option>
<option value="7" disabled selected>Polar Bear</option>
<option value="8" disabled selected>Spectacled Bear</option>
</select>
Such that I appear like this,
So, now users cannot remove the selected options.
But when you are retrieving the selected values, make sure you are adding the selected values like this.
var selected = $(".my_select_box").val();
var alreadySelected = ['5', '6', '7', '8']
var totalSelected = selected.concat(alreadySelected);
Now, it's ready! You can play with it.
Upvotes: 2