views:

15

answers:

1

I would like to size a select list based on the width needed for the selected index(string). Say for example I have a list with 3 strings, short, medium, loooooong; I don't want the select list to automatically be as wide as its largest element, rather it should be as wide as its selected element.

The first method I tried: document.getElementById('selectList').style.width = (selectedText.length * 6) + 'px'; where selectedText is a string and 6 was a poor estimation of the width of a character. Without a monospaced font this does not work correctly.

The next method I tried was to set the innerHTML of an off screen div (top:-9999px) to the selected index and then: document.getElementById('selectList').style.width = document.getElementById('hiddenDiv').offsetWidth; The problem with this method is that the width was also not correct, some really long strings made the select list way to long compared to the actual selected string.

Any ideas how I can dynamically size this select list based on the string width/length?

+1  A: 

You can have a hidden span that is filled with the selected option value on change, grab its width, then set the select list to that width.

Demo

cnanney
I just realized I used jQuery for the demo and you made no mention of jQuery in the question. So, if you were using jQuery, there's one way to do it :)
cnanney
If you actually convert your method to javascript, it does not work. jQuery does some magic to get this to work, and after looking at the jQuery source I could not quite verify how it was doing it.You can't get the css width of an hidden span in javascript, I think you need to get its clientHeight.
sgarman