Reputation: 149
I have used the select2 tool in my application, it is working fine when there are enough options to display. I have a condition where sometimes the options might be empty, at that time, I need to throw an alert text or warning instead of showing the blank select2 search box?
Is there a way to do so, I tried hiding the search box and disabling it but still the empty search box is being displayed there.
html
<select class="js-example-basic-multiple" id="FirstSelect" name="firstselectbox" multiple="multiple"></select>
.js file
if (options.length == 0) {
$("#alerttext").text("No options to display");
$("#FirstSelect").prop("disabled", true);
$('#FirstSelect').hide();
$("#FirstSelect").select2({
minimumResultsForSearch: -1
});
}
Upvotes: 1
Views: 355
Reputation: 4638
Use following code this should work for you.
var select2 = $("#FirstSelect").select2();
var listValue = $("#FirstSelect")[0].length;
if (listValue == 0) {
select2.onSelect = (function(fn) {
$(".select2-search").hide();
})(select2.onSelect);
}
Check Out this Codepen
Upvotes: 3