Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/Show Select2

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.

like image 619
Marquinho Peli Avatar asked Jan 05 '17 03:01

Marquinho Peli


People also ask

How do you focus Select 2?

$('#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.

How do I stop select2 from auto selecting the first option?

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.


3 Answers

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

like image 171
Bindrid Avatar answered Oct 09 '22 15:10

Bindrid


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.

like image 10
Pila 77 Avatar answered Oct 09 '22 14:10

Pila 77


This worked for me..

jQuery("#my-select2").select2().next().hide();
like image 9
Zein Avatar answered Oct 09 '22 13:10

Zein