[css] set the width of select2 input (through Angular-ui directive)

I have problem making this plunkr (select2 + angulat-ui) work.

http://plnkr.co/edit/NkdWUO?p=preview

In local setup, I get the select2 work, but I cannot set the width as described in the docs. It is too narrow to be used.

enter image description here

Thank you.

EDIT: Never mind that plnkr, I found a working fiddle here http://jsfiddle.net/pEFy6/

It looks like it is the behavior of select2 to collapse to the width of first element. I could set the width through bootstrap class="input-medium" .Still not sure why angular-ui doesn't take config parameters.

The answer is


Add width resolve option to your select2 function

$(document).ready(function() { 
        $("#myselect").select2({ width: 'resolve' });           
});

After add below CSS to your stylesheet

.select2-container {
width: 100% !important;
}

It will sort the issue


On a recent project built using Bootstrap 4, I had tried all of the above methods but nothing worked. My approach was by editing the library CSS using jQuery to get 100% on the table.

 // * Select2 4.0.7

$('.select2-multiple').select2({
    // theme: 'bootstrap4', //Doesn't work
    // width:'100%', //Doesn't work
    width: 'resolve'
});

//The Fix
$('.select2-w-100').parent().find('span')
    .removeClass('select2-container')
    .css("width", "100%")
    .css("flex-grow", "1")
    .css("box-sizing", "border-box")
    .css("display", "inline-block")
    .css("margin", "0")
    .css("position", "relative")
    .css("vertical-align", "middle")

Working Demo

_x000D_
_x000D_
$('.select2-multiple').select2({_x000D_
        // theme: 'bootstrap4', //Doesn't work_x000D_
        // width:'100%',//Doens't work_x000D_
        width: 'resolve'_x000D_
    });_x000D_
    //Fix the above style width:100%_x000D_
    $('.select2-w-100').parent().find('span')_x000D_
        .removeClass('select2-container')_x000D_
        .css("width", "100%")_x000D_
        .css("flex-grow", "1")_x000D_
        .css("box-sizing", "border-box")_x000D_
        .css("display", "inline-block")_x000D_
        .css("margin", "0")_x000D_
        .css("position", "relative")_x000D_
        .css("vertical-align", "middle")
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="table-responsive">_x000D_
    <table class="table">_x000D_
        <thead>_x000D_
        <tr>_x000D_
            <th scope="col" class="w-50">#</th>_x000D_
            <th scope="col" class="w-50">Trade Zones</th>_x000D_
        </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
        <tr>_x000D_
            <td>_x000D_
                1_x000D_
            </td>_x000D_
            <td>_x000D_
                <select class="form-control select2-multiple select2-w-100" name="sellingFees[]"_x000D_
                        multiple="multiple">_x000D_
                    <option value="1">One</option>_x000D_
                    <option value="1">Two</option>_x000D_
                    <option value="1">Three</option>_x000D_
                    <option value="1">Okay</option>_x000D_
                </select>_x000D_
            </td>_x000D_
        </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
_x000D_
_x000D_
_x000D_


select2 V4.0.3

<select class="smartsearch" name="search" id="search" style="width:100%;"></select>

add method container css in your script like this :

$("#your_select_id").select2({
      containerCss : {"display":"block"}
});

it will set your select's width same as width your div.


With > 4.0 of select2 I am using

$("select").select2({
  dropdownAutoWidth: true
});

These others did not work:

  • dropdownCssClass: 'bigdrop'
  • width: '100%'
  • width: 'resolve'

In my case the select2 would open correctly if there was zero or more pills.

But if there was one or more pills, and I deleted them all, it would shrink to the smallest width. My solution was simply:

$("#myselect").select2({ width: '100%' });      

Setting width to 'resolve' didn't work for me. Instead, i added "width:100%" to my select, and modified the css like this :

.select2-offscreen {position: fixed !important;}

This was the only solution that worked for me (my version is 2.2.1) Your select will take all the available place, it is better than using

class="input-medium"

from bootstrap, because the select is always staying in the container, even after resizing the window (responsive)


You can try like this. It works for me

$("#MISSION_ID").select2();

On hide/show or ajax request, we have to reinitialize the select2 plugin

For example:

$("#offialNumberArea").show();
$("#eventNameArea").hide();

$('.selectCriteria').change(function(){
    var thisVal = $(this).val();
    if(thisVal == 'sailor'){
        $("#offialNumberArea").show();
        $("#eventNameArea").hide();
    }
    else
    {
        $("#offialNumberArea").hide();
        $("#eventNameArea").show();
        $("#MISSION_ID").select2();
    }
});

This is an old question but new info is still worth posting...

Starting with Select2 version 3.4.0 there is an attribute dropdownAutoWidth which solves the problem and handles all the odd cases. Note it is not on by default. It resizes dynamically as the user makes selections, it adds width for allowClear if that attribute is used, and it handles placeholder text properly too.

$("#some_select_id").select2({
    dropdownAutoWidth : true
});

Easier CSS solution independent from select2

//HTML
<select id="" class="input-xlg">
</select>
<input type="text" id="" name="" value="" class="input-lg" />

//CSS
.input-xxsm {
  width: 40px!important; //for 2 digits 
}

.input-xsm {
  width: 60px!important; //for 4 digits 
}

.input-sm {
  width: 100px!important; //for short options   
}

.input-md {
  width: 160px!important; //for medium long options 
}

.input-lg {
  width: 220px!important; //for long options    
}

.input-xlg {
  width: 300px!important; //for very long options   
}

.input-xxlg {
  width: 100%!important; //100% of parent   
}

Wanted to add my solution here as well. This is similar to Ravindu's answer above.

I added width: 'resolve', as a property within the select2:

    $('#searchFilter').select2({
        width: 'resolve',
    });

Then I added a min-width property to select2-container with !important:

.select2-container {
    min-width: 100% !important;
}

On the select element, the style='100px !important;' attribute needed !important to work:

<select class="form-control" style="width: 160px;" id="searchFilter" name="searchfilter[]">

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?