Change select2 open position | select2 open upwards

select2 open upwards

Customization is the most important requirement for form controls. It’s better to use plugin to customize dropdown and from those I prefer to use select2 | The jQuery replacement for select boxes.

Select2 plugin works perfect in most of scenario until we use it in popup.

Issue with select2 plugin?

Plugin don’t provide option to set its parent container for dropdown position. It means it calculate top and bottom position of dropdown based on window offset not the container offset.

The best possible fix for this issue is to reduce the height of dropdown and open it upward. Height we can reduce using below CSS.

.select2-container--default .select2-results>.select2-results__options{max-height:75px !important;}

But there is no option to set open direction in select2 plugin.

What is the solution?

Since there is no options to instruct plugin for open direction, there are two approaches we can use to achieve the target.

Change in select2 plugin

To edit select2 plugin we need developer JS version, below is the one

https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.js

Now find ._positionDropdown in JS and code just after

var isCurrentlyBelow = this.$dropdown[0].classList.contains('select2-dropdown--below');

Code to add

if(this.$element[0].classList.contains("_openup")){		
	isCurrentlyAbove = true;
	isCurrentlyBelow = false;
}

Now use class named _openup when you want to open select2 dropdown upside.

<select class="_openup" id="country_code">
...
</select>

Hope it will help..

if you hesitate in editing core plugin comment us using Facebook comment we will post the custom code to enable select2 upward direction.