views:

98

answers:

1

I am using Javascript to dynamically add new options to a drop down list and when the list reverts to the selected item with the arrow to the right of it to expand the list, the box containing the selected text is as wide as the widest text in the options list.

So what I would like to do is have the width of the box hug the text if you know what I mean without the redundant white space to the right of the text in the box.

Thanks a lot if anyone can help me with this :-)

+2  A: 

It's easy, just remove the content of hidden options (copy it into option's title) and restore it on select focus.

Code:

<html><head><title>Auto size select</title>

<script>
var resized = false;

function resizeSelect(selected) {
  if (resized) return;
  var sel = document.getElementById('select');
  for (var i=0; i<sel.options.length; i++) {
    sel.options[i].title=sel.options[i].innerHTML;
    if (i!=sel.options.selectedIndex) sel.options[i].innerHTML='';
  }
  resized = true;
  sel.blur();
}

function restoreSelect() {
  if (!resized) return;
  var sel = document.getElementById('select');
  for (var i=0; i<sel.options.length; i++) {
    sel.options[i].innerHTML=sel.options[i].title;
  }  
  resized = false;
}
</script>

</head>
<body onload="resizeSelect(this.selectedItem)">
<select id="select" 
  onchange="resizeSelect(this.selectedItem)"
  onblur="resizeSelect(this.selectedItem)"
  onfocus="restoreSelect()">
<option>text text</option>
<option>text text text text text</option>
<option>text text text </option>
<option>text text text text </option>
<option>text</option>
<option>text text text text text text text text text</option>
<option>text text</option>
</select>
</body></html>
Pedro Ladaria
Thanks Pedro! Cool solution :-)
Andy
+1 Thanks Pedro - I hope this works across all browsers :)
Faisal Vali