Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop down list width fit selected item text

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?

like image 975
formatc Avatar asked Apr 24 '12 22:04

formatc


2 Answers

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/

like image 119
Ethan Brown Avatar answered Sep 22 '22 19:09

Ethan Brown


Variation on @Ethan Brown's answer, with the .val() corrected to .text() and a dynamically-created select so your page isn't polluted:

HTML:

<select id="sel">
  <option>Short</option>
  <option>Really, Really, Really Long</option>
</select>​

JS:

function setSelectWidth(selector) {
    var sel = $(selector);
    var tempSel = $("<select style='display:none'>")
        .append($("<option>").text(sel.find("option:selected").text()));
    tempSel.appendTo($("body"));

    sel.width(tempSel.width());

    tempSel.remove();
}

$(function() {
    setSelectWidth("#sel");

    $("#sel").on("change", function() {
        setSelectWidth($(this));
    });
});

Fiddle:

http://jsfiddle.net/kn9DF/242/

Tested on Chrome 39, FF 36, IE 11.

like image 27
Ian Kemp Avatar answered Sep 23 '22 19:09

Ian Kemp