I want to hide or show my select2, but I can't find a method in the API. I'm using a workaround, hiding the parent, like this:
$(document).on('change', '.country', function () {
if ($(this).val() == $(this).data('current-countryCode')) {
$('#states').parent().show();
}
else {
$('#states').parent().hide();
}
});
But I'd like to know if anyone could help or if even exists such a method in the API.
$('#id'). select2('open'); will set focus and open the select2 ready for search. $('#id'). select2('focus'); will set the focus on select2 but not select2 will be not opened for search.
This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.
I do a similar thing, however I hide the select2 container which is always the next node over from the start point so it would look like.
$(document).on('change', '.country', function () {
if ($(this).val() == $(this).data('current-countryCode')) {
$('#states').next(".select2-container").show();
}
else {
$('#states').next(".select2-container").hide();
}
});
So I have been taking the same approach you have
The problem is that you have to hide all the items associated with the select2 dropdown (all that the plugin generates to do the magic).
I solved using a div that contains the select2 dropdown and show/hide this div.
This worked for me..
jQuery("#my-select2").select2().next().hide();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With