Question

I've got an HTML "select" element which I'm updating dynamically with code something like this:

var selector = document.getElementById('selectorId');    
for (var i = 0; i < data.length; ++i)
{
  var opt = document.createElement('option');
  opt.value = data[i].id;
  opt.text = data[i].name;
  selector.appendChild(opt);
}

Works fine in Firefox, but IE7 doesn't resize the list box to fit the new data. If the list box is initially empty (which it is in my case), you can hardly see any of the options I've added. Is there a better way to do this? Or a way to patch it up to work in IE?

Was it helpful?

Solution

Set the innerHTML property of the option objects, instead of their text.

var selector = document.getElementById('selectorId');    
for (var i = 0; i < data.length; ++i)
{
  var opt       = document.createElement('option');
  opt.value     = data[i].id;
  opt.innerHTML = data[i].name;
  selector.appendChild(opt);
}

Works on IE6, just tested. Does not break on FF3, so I guess this is it.

(I chose "innerHTML" because this works across browsers. To set the literal text, you have to use "innerText" on IE, and "textContent" on FF, and you probably have to test it elsewhere as well. As long as there are no special characters (&, <, >) in the "name" properties, "innerHTML" will be enough.)

OTHER TIPS

You don't need to manipulate DOM for this. Try this instead

var selector = document.getElementById('selectorId');  
for (var i = 0; i < data.length; ++i) {
    selector.options[selector.options.length] = new Option(data[i].name, data[i].id);
}

After adding the option element, force select.style.width to auto, even if it is already auto.

If this doesn't work, clear select.style.width to "" and then restore select.style.width to auto again.

That makes Internet Explorer recalculate the optimal width of select elements.

Set the width of the select box explicitly, using eg. a CSS ‘width’ style, instead of letting the browser guess the width from its contents.

You could try replacing the entire select element from generated html code, or as a hack removing the element from the DOM and readding it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top