Search code examples
javascriptjquery-select2jquery-select2-4

Move the search box in a select2


I am trying to move the search box in a select2, so that it will appear on the bottom of the results when the select is opening above and on the top when the select2 is opening below.

It should basically look like this:

enter image description hereenter image description here

I have tried the following and although the moving part works, I cna not find a way to attach it to the proper event. if you scroll the page and the select go from above to belove, the search box will not change back because it is attacched to the select2:open event.

Is there an event (like render maybe) that I can use to make sure that I can change the position of the search box every time the select2 moves?

OR

How can I move the search box to always be at the bottom when select2 opens above and at the top when it opens below?

you can see it in this https://codepen.io/anon/pen/ZaxZOa better than the snippet because you can also scroll here.

$( document ).ready( function() {
	$( '.js-example-basic-single' ).select2();
  
   //$('.select2-results').insertAfter('.select2-search--dropdown');
  
  $('.js-example-basic-single').on('select2:open', function(){
 
    $('.select2-dropdown--above .select2-search--dropdown').insertAfter('.select2-results');
  });
  
});
.form-control {

	width: 360px;
	height: 34px;
	padding: 6px 12px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>

<h1>Select2</h1>

<div class="col">

<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  
<label for="js-example-basic-single">Select2: select a US state</label><br>
<select class="js-example-basic-single form-control" id="js-example-basic-single">

<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
</select>

</div>


Solution

  • I solved this with CSS flexbox. Making the selct2 a flex and then changing the order of the search andresult divs.

    .select2-dropdown--above{
      display: flex; flex-direction: column;
    }
    .select2-dropdown--above .select2-search--dropdown{
      order: 2;
    }
    .select2-dropdown--above .select2-results {
    order: 1; 
    }
    
    .select2-dropdown--below{
      display: flex; flex-direction: column;
    }
    .select2-dropdown--below .select2-search--dropdown{
      order: 1;
    }
    .select2-dropdown--below .select2-results {
    order: 2; 
    }