select2 with bootstrap theme - inside collapse
Asked Answered
F

2

6

I cannot get the select2 dropdown to fit parent container (collapse) when initialized hidden. I understand this is not a bug, because select2 was not able to calculate the parent width. But I couldn't overcome this. I need it to be 100% to the parent.

<div class="panel panel-default">
  <div class="panel-body">
    <div class="btn-toolbar">
      <button class="btn btn-default" data-toggle="collapse" data-target="#collapse-select2" aria-expanded="false">Toggle</button>
    </div>
    <div class="collapse" id="collapse-select2">
      <select class="form-control" data-role="select2">
        <option value="1">Option #1</option>
        <option value="2">Option #2</option>
        <option value="3">Option #3</option>
      </select>
    </div>
  </div>
</div>

Fiddle: here

Can anybody please help?

Faucal answered 5/7, 2016 at 5:41 Comment(1)
did it work for you? stackoverflow.com/help/why-vote – Triglyph
T
11

actually quite simple solution:

1. CSS only solution
give .select2 100% width and override with !important like this:

.select2 {
  width: 100%!important; /* overrides computed width, 100px in your demo */
}

here's also your updated fiddle https://jsfiddle.net/1agwbfmy/6/


2. style tag for select
another way to do it, as written in documentation is to give width to <select> element with style and it will get the attribute from there:
<select class="form-control" data-role="select2" style="width:100%">


3. plugin configuration
lastly, you can set the width when calling the plugin in jQuery (as written in old docs):

$('select[data-role="select2"]').select2({
    theme: 'bootstrap',
    width: '100%'
});
Triglyph answered 5/7, 2016 at 5:47 Comment(3)
I went with the *3*rd option as I initialize it globally and wanted every control to inherit this. – Faucal
You would get the same result with 1st solution too as .select2 would apply the width globally to all selects with that class (and as long as you use this class to bind select2 js, it would work just fine) – Triglyph
But I prefer JS over CSS 😊 – Faucal
Y
4

Use width: '100%' property in config.

$('[data-role="select2"]').select2({
   width: '100%',
   ...
});
Yungyunick answered 5/7, 2016 at 6:30 Comment(1)
yours is also correct but I chose @moped's for explanation and agility. :) – Faucal

© 2022 - 2024 β€” McMap. All rights reserved.