Ad

How To Make The Selected Option The Width Of The Current Selected Option's Text?

- 1 answer

I am trying to make the Select Option to have the width of the current Selected Option.

My code is the standard HTML for a Select Option dropdown:

<select name="search_options">
  <option value="all">All</option>
  <option value="entertainment">Entertainment</option>
  <option value="newsandpolitics">News &amp; Politics</option>
  <option value="sports">Sports</option>
  <option value="lifestyle">Lifestyle</option>
  <option value="health">Health</option>
  <option value="scienceandtech">Science &amp; Tech</option>
</select>

I have been trying to do this with just CSS or Javascript, with no JQuery, and I can't figure it out.

I have found several fiddles with JQuery already, but no CSS/Javascript ones.

http://jsfiddle.net/5AANG/4/

http://jsfiddle.net/qqcc5/

Is there any way to achieve this, identical with the above 2 fiddles, using just CSS or pure Javascript?

Any pointers in the right direction would be great.

Ad

Answer

Based on your second link you can do it like this:

var selectId = document.getElementById("yourSelect");

selectId.onchange=function(){
   var selectedValue = selectId.options[selectId.selectedIndex].value; 
   var selectedText = selectId.options[selectId.selectedIndex].text;

   selectId.style.width = 20 + (selectedText.length * 8) + "px";
}

Test: http://jsfiddle.net/ndquxquu/

Ad
source: stackoverflow.com
Ad