Reputation: 171
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:
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?
Upvotes: 2
Views: 1200
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();
Upvotes: 2