5

How to force select2 to always dropdown and never dropup?

I tried this solution but it's not working: This doesn't work

$("#e1").select2()
.on('select2-open', function() {

// however much room you determine you need to prevent jumping
        var requireHeight = 600;
        var viewportBottom = $(window).scrollTop() + $(window).height();

        // figure out if we need to make changes
        if (viewportBottom < requireHeight) 
        {           
            // determine how much padding we should add (via marginBottom)
            var marginBottom = requireHeight - viewportBottom;

            // adding padding so we can scroll down
            $(".aLwrElmntOrCntntWrppr").css("marginBottom", marginBottom + "px");

            // animate to just above the select2, now with plenty of room below
            $('html, body').animate({
                scrollTop: $("#e1").offset().top - 10
            }, 1000);
        }
    });

jsFiddle

Community
  • 1
  • 1
brunodd
  • 2,474
  • 10
  • 43
  • 66

2 Answers2

6

This worked for me:

$.fn.select2.amd.require([
  'select2/selection/multiple',
  'select2/selection/search',
  'select2/dropdown',
  'select2/dropdown/attachContainer',
  'select2/dropdown/closeOnSelect',
  'select2/utils'
], function (MultipleSelection, Search, Dropdown, AttachContainer, CloseOnSelect, Utils) {
  var SelectionAdapter = Utils.Decorate(
    MultipleSelection,
    Search
  );

  var DropdownAdapter = Utils.Decorate(
    Utils.Decorate(
      Dropdown,
      CloseOnSelect
    ),
    AttachContainer
  );

  $('#e1').select2({
    dropdownAdapter: DropdownAdapter
  });
});

jsFiddle

brunodd
  • 2,474
  • 10
  • 43
  • 66
  • is this permanent solution and where i put this code in the select2.js file or my js file – JP.dev Jul 14 '16 at 11:27
  • @j.code I found the easiest way, was to define each require as a variable e.g. `var Utils = $.fn.select2.amd.require('select2/utils');` then create the `DropdownAdapter` globally. This allowed me just include `dropdownAdapter: DropdownAdapter` wherever I needed it. Hope that helps. – PanPipes Apr 14 '17 at 10:50
  • For anyone else that is curious, the `SelectionAdapter` is meant to be used like `selectionAdapter: SelectionAdapter` in select2 call. However I don't believe it is needed for this solution. – PanPipes Apr 14 '17 at 10:56
  • Take a look at the following answer: https://stackoverflow.com/questions/19983601/prevent-select2-from-flipping-the-dropdown-upward/47912914#47912914 – andreivictor Dec 20 '17 at 19:19
0

I'm using Select2 v4.0.5 (the minified version)

Open select2.js

Search for c?!j&&k&&c&&(e="below"):e="above"

To always drop down, replace "above" with "below"

To always drop up, replace "below" with "above"