Auto resizing the SELECT element according to selected OPTION's width

Th3Alchemist picture Th3Alchemist · Nov 20, 2013 · Viewed 85k times · Source

I've got this select element with different option in it. Normally the select element would get its width from the biggest option element, but I want the select element to have the default option value's width which is shorter. When the user selects another option, the select element should resize itself so the whole text is always visible in the element.

$(document).ready(function() {
    $('select').change(function(){
        $(this).width($('select option:selected').width());
    });
});

Problem:

  • On Chrome (Canary) it always gets a width returned of 0.
  • On Firefox the width get's added and not resized when selected a shorter option.
  • Safari: Same result as Chrome.

Demo @ JSFiddle

Answer

kmas picture kmas · Nov 20, 2013

You are right there is no easy or built-in way to get the size of a particular select option. Here is a JsFiddle that does what you want.

It is okay with the latest versions of Chrome, Firefox, IE, Opera and Safari.

I have added a hidden select #width_tmp_select to compute the width of the visible select #resizing_select that we want to be auto resizing. We set the hidden select to have a single option, whose text is that of the currently-selected option of the visible select. Then we use the width of the hidden select as the width of the visible select. Note that using a hidden span instead of a hidden select works pretty well, but the width will be a little off as pointed out by sami-al-subhi in the comment below.

$(document).ready(function() {
  $('#resizing_select').change(function(){
    $("#width_tmp_option").html($('#resizing_select option:selected').text()); 
    $(this).width($("#width_tmp_select").width());  
  });
});
#resizing_select {
  width: 50px;
} 
 
#width_tmp_select{
  display : none;
} 
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

<select id="resizing_select">
  <option>All</option>
  <option>Longer</option>
  <option>A very very long string...</option>
</select>

<select id="width_tmp_select">
  <option id="width_tmp_option"></option>
</select>