MarcBalaban
MarcBalaban

Reputation: 75

select2.js and chosen.js not rendering properly on dropdown menu

Using bootstrap in a dropdown menu and using relatively simple code:

$('#platform-picker').select2()

When the dropdown is not visible and the select2 function is executed -- the results are incorrect and look like this:

incorrect

When the dropdown is visible -- the results are 100% correct:

correct

Upvotes: 2

Views: 195

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41699

Both Select2 and Chosen rely on the browser giving an accurate value for the width of the select box in order to set the size of the one that is displayed. When the box is initially hidden (such as when a dropdown is closed) the width given by the browser is typically null or 0, which is either not helpful (what's a null width?) or completely wrong (a width of 0? really?).

The solution for Select2 is to set the width in-line in the <select> element before initializing it. Select2 will use this value when setting the width of the new box.

<select style="width: 100%"></select>

An alternative solution is to not initialize Select2 until the dropdown is shown by listening to the shown event triggered by Bootstrap.

Upvotes: 1

Related Questions