Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 fullwidth in hidden div?

Assume I have a select2 box inside a hidden div like this:

<form >   
 <div id="agent007">
  <select name="slimy" id="slimy">
   <option>Good</option>
   <option>Bad</option>
  </select>
 </div>
</form>

Where the selection box has full width and the div is hidden

select{
  width:100%
}

div{
  display:none;
}

When I make the div visible, then the selection box has no full width.

$(document).ready(function(){
  $('#slimy').select2();
  $('#agent007').show();
});

How can I make a select2 box full width that was hiding in a invisible container?

Here is a jFiddle

like image 712
Adam Avatar asked Jan 28 '23 14:01

Adam


1 Answers

You can set the width programmatically through the Select2 Configuration API. The docs make it clear that sometimes this is your best option:

Select2 will try to match the width of the original element as closely as possible. Sometimes this isn't perfect, in which case you may manually set the width configuration option

$(document).ready(function(){
  $('#slimy').select2({'width':'100%'});
  $('#agent007').css('display','block');
});
select{
  width:100%
}

div{
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>


<form >   
 <div id="agent007">
  <select name="slimy" id="slimy">
   <option>Good</option>
   <option>Bad</option>
  </select>
 </div>
</form>

Note: due to a conflict between jQuery's show() and stack snippets, I used css('display','block') here as a workaround

like image 143
Eaten by a Grue Avatar answered Jan 31 '23 08:01

Eaten by a Grue