soomro
soomro

Reputation: 171

Select2 not full width or block when using toggle()

I have some selects that are Select2:s (using the plugin select2). What I want is that when the first select2 is changed and it is a specific option, it will display another select2. At first when the page is loaded all of the hidden select2s are hidden with jQuery's .toggle(). This is because I use bootstrap and have every select inside a .form-group and I don't want to use more classes than needed. Therefore I use this:

$("#secondSelect").parents(".form-group").toggle();

I then use this code to display the next select2:

$("#firstSelect").on("change", function(e) {
    if ($(this).val() == "specificValue") {
        $("#secondSelect").parents(".form-group").toggle();
    } else {
        $("#secondSelect").parents(".form-group").toggle();
    }
});

But the problem is that the second select2 is not displaying properly inside the .form-group. It looks like this: enter image description here

It is not full width and in line with the label.

The strange thing is that when I use the chrome inspector and use the console to type in the .toggle() code, this is not a problem. Why does it not display correctly?

JSFIDDLE

Upvotes: 2

Views: 1200

Answers (1)

alpha-before-beta
alpha-before-beta

Reputation: 514

This problem occurs because when you call .select2 the elements are hidden and therefore do not have widths set on them. Initialize before hiding the elements and the widths will resolve correctly.

Move these lines to the bottom of your js code...

$("#program").parents(".form-group").toggle();
$("#year").parents(".form-group").toggle();

updated fiddle

Upvotes: 2

Related Questions