Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 with bootstrap theme - inside collapse

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?

like image 337
VPZ Avatar asked Jul 05 '16 05:07

VPZ


1 Answers

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%'
});
like image 122
moped Avatar answered Oct 12 '22 14:10

moped