Marquinho Peli
Marquinho Peli

Reputation: 5139

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.

Upvotes: 44

Views: 60728

Answers (7)

Vinicius Pasqualini
Vinicius Pasqualini

Reputation: 1

My workaround was to first destroy the select2 then hide the select

  $("#select").select2('destroy');
  $("#select").attr('style','display: none');

And to show it again I remove the display: none and recreate the select2

$("#select").attr('style', '');
$("#select").select2();

Obs: Make sure to use the same configuration of select2 when recreating it, or use the data-* attributes.

Upvotes: 0

IlludiumPu36
IlludiumPu36

Reputation: 4304

Put the Select2 into a div. In this case I'm just declaring a div #select as a Select2:

$('#select').select2();

<div id='select_parent'><div id='select'></div></div>

Show/hide the div containing the Select2:

$('#select_parent').hide();

Upvotes: 2

Mircea Voivod
Mircea Voivod

Reputation: 721

Easier by extending $.fn

    $.fn.toggleSelect2 = function(state) {
        return this.each(function() {
            $.fn[state ? 'show' : 'hide'].apply($(this).next('.select2-container'));
        });
    };

Then simply call it on the select element.

$('select').toggleSelect2(true); //Show

or

$('select').toggleSelect2(false); //hide

Upvotes: 2

Zein
Zein

Reputation: 113

This worked for me..

jQuery("#my-select2").select2().next().hide();

Upvotes: 10

Pila 77
Pila 77

Reputation: 415

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.

Upvotes: 11

Skriptas
Skriptas

Reputation: 889

One more workaround – you can add a class to select2 object at creation

$("#user-box").select2({
    containerCssClass : "show-hide"
});

...and then hide it when you want with

$(".show-hide").parent().parent().hide();

Upvotes: 2

Bindrid
Bindrid

Reputation: 3735

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

Upvotes: 60

Related Questions