Select2 change container position
Asked Answered
H

2

9

How can I adjust the position of Select2 container so that the search box is position right over the original select element like in this website

http://www.jobnisit.com/en

It look cleaner in terms of UI in my opinion.

Ps. sorry, I can't post the image now.

Hectometer answered 22/7, 2015 at 7:21 Comment(2)
This question is too broad; can you add details and code to your question to help clarify?Petropavlovsk
@Petropavlovsk I have no specific code but normally the default Select2 (a single select to be specific) when click, there will be a search box appear below the selected list. My question is there a way to position the search box right over the selected list. I've seen the mentioned website (jobnisit.com/en) did it this way but I can't figure out how they do it.Hectometer
P
13

There is 2 ways to do this.

1) With css:

.select2-dropdown--below {
    top: -2.8rem; /*your input height*/
}

This will not affect a container (.select2-container), but will move dropdown and search field, so you will have a desired effect.

2) With js:

$('select').select2().on('select2:open', function() {
  var container = .$('.select2-container').last();
  /*Add some css-class to container or reposition it*/
});

This code attaches a handler to 'select2:open' event, which will be fired every time when user opens a dropdown. This method is better if you have more than one select on page.

Tested with select2 4.0.0

Projection answered 12/8, 2015 at 15:10 Comment(6)
Thanks @Gennady, the CSS solution works for me. Before that I set the negative top to the .select2-dropdown. Seem to have the same effect. Will play with the js solution as suggested.Hectometer
The CSS solution can not work when the text box is position above because in that case the search box is on top of the select. And the Javascript solution does not work when the position is automatically changed in case of scrolling of the page.Theurer
the css not working with v4.0.13, the dropdown is closed immediately after opens!Cazzie
same for the js solutionCazzie
@Cazzie I doubt changing CSS may lead to dropdown closed immediatelyProjection
@GennadyDogaev I asked a full question with sample snippet here #64422831Cazzie
O
12

The proper way of positioning the dropdown is using the core feature provided by select2 plugin.

It provides us with 'dropdownParent' property to place to dropdown inside the particular element

select field: #edit-field-job-skillsets-tid

parent item: div.form-item-field-job-skillsets-tid

jQuery("#edit-field-job-skillsets-tid").select2(
  {dropdownParent: jQuery('div.form-item-field-job-skillsets-tid')}
 );
Obediah answered 5/1, 2016 at 7:12 Comment(1)
@jjospratik Thanks sir,Baneberry

© 2022 - 2024 — McMap. All rights reserved.