[jquery] How to expand 'select' option width after the user wants to select an option

Maybe this is an easy question, maybe not. I have a select box where I hardcode with width. Say 120px.

_x000D_
_x000D_
<select style="width: 120px">_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
  <option>ABC</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

I want to be able to show the second option so that the user can see the full length of the text.

Like everything else. This works fine in Firefox, but doesn't work with Internet Explorer6.

This question is related to jquery css html-select content-length

The answer is


Sample

function PopulateDropdown() {
    $.ajax({
        type: "POST",
        url: "../CommonWebService.asmx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("select[id^='MyDropDown']").empty();
            $.each(msg.d, function () {
                $("select[id^='MyDropDownSelect']").append($("<option></option>").val(this['IdIndexDataType']).html(this['DataTypeName']));
            }); 
            $("select[id^='MyDropDown']").css("width", "auto");  
        },
        error: function (e1) {
            alert("Error - " + e1.toString());
        }
    });
}

The below code will solve your problem of dropdownlist width by adding this code after insertion of Data to dropdownlist.

$("select[id^='MyDropDown']").css("width", "auto");

Sample

function PopulateDropdown() {
    $.ajax({
        type: "POST",
        url: "../CommonWebService.asmx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("select[id^='MyDropDown']").empty();
            $.each(msg.d, function () {
                $("select[id^='MyDropDownSelect']").append($("<option></option>").val(this['IdIndexDataType']).html(this['DataTypeName']));
            }); 
            $("select[id^='MyDropDown']").css("width", "auto");  
        },
        error: function (e1) {
            alert("Error - " + e1.toString());
        }
    });
}

The below code will solve your problem of dropdownlist width by adding this code after insertion of Data to dropdownlist.

$("select[id^='MyDropDown']").css("width", "auto");

Place it in a div and give it an id

<div id=myForm>

then create a really really simple css to go with it.

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

That's all you need.


A simple solution I used for an existing site in IE (using jQuery, but I can post back with eventListener code if you really don't know JS that well) is the following:

if (jQuery.browser.msie) {
  jQuery('#mySelect').focus(function() {
    jQuery(this).width('auto');
  }).bind('blur change', function() {
    jQuery(this).width('100%');
  });
};

Of course, use a variable (var cWidth = jQuery('#mySelect').width();) to store the previous width, but this is all that was required for ours to work as you'd expect.


This mimics most of the behavior your looking for:

  <!--

     I found this works fairly well.

  -->

  <!-- On page load, be sure that something else has focus. -->
  <body onload="document.getElementById('name').focus();">
  <input id=name type=text>

  <!-- This div is for demonstration only.  The parent container may be anything -->
  <div style="height:50; width:100px; border:1px solid red;">

  <!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->
  <select
   style="width:96px; position:absolute; z-index:+1;"
   onactivate="this.style.width='auto';"
   onchange="this.blur();"
   onblur="this.style.width='96px';">
  <!-- "activate" happens before all else and "width='auto'" expands per content -->
  <!-- Both making a selection and moving to another control should return static width -->

  <option>abc</option>
  <option>abcdefghij</option>
  <option>abcdefghijklmnop</option>
  <option>abcdefghijklmnopqrstuvwxyz</option>

  </select>

  </div>

  </body>

  </html>

This will override some of the key-press behavior.


Place it in a div and give it an id

<div id=myForm>

then create a really really simple css to go with it.

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

That's all you need.


Very old question but here's the solution. Here you have a working snippet using jquery. It makes use of a temporary auxiliary select into which the selected option from the main select is copied, such that one can assess the true width which the main select should have.

_x000D_
_x000D_
$('select').change(function(){_x000D_
  var text = $(this).find('option:selected').text()_x000D_
  var $aux = $('<select/>').append($('<option/>').text(text))_x000D_
  $(this).after($aux)_x000D_
  $(this).width($aux.width())_x000D_
  $aux.remove()_x000D_
}).change()
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select>_x000D_
  <option>ABC</option>_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery


you can try and solve using css only. by adding class to select

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

for more reference List Box Style in a particular item (option) HTML

Multi Select List Box


Very old question but here's the solution. Here you have a working snippet using jquery. It makes use of a temporary auxiliary select into which the selected option from the main select is copied, such that one can assess the true width which the main select should have.

_x000D_
_x000D_
$('select').change(function(){_x000D_
  var text = $(this).find('option:selected').text()_x000D_
  var $aux = $('<select/>').append($('<option/>').text(text))_x000D_
  $(this).after($aux)_x000D_
  $(this).width($aux.width())_x000D_
  $aux.remove()_x000D_
}).change()
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select>_x000D_
  <option>ABC</option>_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery


you can try and solve using css only. by adding class to select

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

for more reference List Box Style in a particular item (option) HTML

Multi Select List Box


Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery


I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!


I fixed it in my bootstrap page by setting the min-width and max-width to the same value in the select and then setting the select:focus to auto.

_x000D_
_x000D_
select {_x000D_
  min-width: 120px;_x000D_
  max-width: 120px;_x000D_
}_x000D_
select:focus {_x000D_
  width: auto;_x000D_
}
_x000D_
<select style="width: 120px">_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
  <option>ABC</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


This mimics most of the behavior your looking for:

  <!--

     I found this works fairly well.

  -->

  <!-- On page load, be sure that something else has focus. -->
  <body onload="document.getElementById('name').focus();">
  <input id=name type=text>

  <!-- This div is for demonstration only.  The parent container may be anything -->
  <div style="height:50; width:100px; border:1px solid red;">

  <!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->
  <select
   style="width:96px; position:absolute; z-index:+1;"
   onactivate="this.style.width='auto';"
   onchange="this.blur();"
   onblur="this.style.width='96px';">
  <!-- "activate" happens before all else and "width='auto'" expands per content -->
  <!-- Both making a selection and moving to another control should return static width -->

  <option>abc</option>
  <option>abcdefghij</option>
  <option>abcdefghijklmnop</option>
  <option>abcdefghijklmnopqrstuvwxyz</option>

  </select>

  </div>

  </body>

  </html>

This will override some of the key-press behavior.


A simple solution I used for an existing site in IE (using jQuery, but I can post back with eventListener code if you really don't know JS that well) is the following:

if (jQuery.browser.msie) {
  jQuery('#mySelect').focus(function() {
    jQuery(this).width('auto');
  }).bind('blur change', function() {
    jQuery(this).width('100%');
  });
};

Of course, use a variable (var cWidth = jQuery('#mySelect').width();) to store the previous width, but this is all that was required for ours to work as you'd expect.


I fixed it in my bootstrap page by setting the min-width and max-width to the same value in the select and then setting the select:focus to auto.

_x000D_
_x000D_
select {_x000D_
  min-width: 120px;_x000D_
  max-width: 120px;_x000D_
}_x000D_
select:focus {_x000D_
  width: auto;_x000D_
}
_x000D_
<select style="width: 120px">_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
  <option>ABC</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery


I improved the cychan's solution, to be like that:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

The PNGs used in css classes are uploaded here...

And you still need JQuery.....


I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!


I improved the cychan's solution, to be like that:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

The PNGs used in css classes are uploaded here...

And you still need JQuery.....


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

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 html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery

Examples related to content-length

How to expand 'select' option width after the user wants to select an option