Javascript – Drop down list width fit selected item text

asp.net-mvccsshtmljavascript

Is there a way in javascript/jquery or css to make html <select>/@Html.DropDownList auto width so it fits currently selected item, I tried with diplay:inline-block and width:auto but width always seems to fit largest item on list?

Best Answer

My answer is similar to D3mon-1stVFW's, but instead uses a hidden drop-down to set the width on dynamically. As long as you use the same styling for your hidden and "real" one, it should account for different font sizes, decoration, etc. Here's the HTML:

<!-- this is our hidden "template" drop-down that we'll
     use to determine the size of our "real" one -->
<select id="template" style="display:none;">
  <option id="templateOption"></option>
</select>
<!-- this is our "real" template that will be re-sized -->
<select id="sel">
  <option>Short</option>
  <option>Really, Really, Really Long</option>
</select>​

And the Javascript:

function setSelectWidth() {
  var sel = $('#sel');
  $('#templateOption').text( sel.val() );
  // for some reason, a small fudge factor is needed
  // so that the text doesn't become clipped
  sel.width( $('#template').width() * 1.03 );
}

$(document).ready( function() {
  setSelectWidth();

  $('#sel').change( function() {
    setSelectWidth();
  } );​    
});

JSFiddle here: http://jsfiddle.net/kn9DF/1/