Thursday, September 14, 2006

IE doesn't show option text when dynamically creating an optgroup

I dealt with a bit of a headache tonight trying to figure out why Internet Explorer 6 wouldn't display any option text if I created an option within an optgroup dynamically (using Javascript). It turns out that you have to set the innerText property of the option before appending it to the optgroup. Just setting the label or text properties of the option is not enough, you need to set innerText, like so:

select_obj = document.getElementById('my_select_box_id');
optgroup_obj = document.createElement('optgroup');
option_obj = document.createElement('option');

option_obj.label = 'option label';
option_obj.value = 'option value';

if ( typeof(option_obj.innerText) != 'undefined' ) {
option_obj.innerText = 'option label';
}
else {
option_obj.text = 'option label';
}

optgroup_obj.appendChild(option_obj);
select_obj.appendChild( optgroup_obj );

8 comments:

Anonymous said...

thanks a lot for that posting - had caused me some headache as well.

Anonymous said...

thnx, it saved me lots of time

Anonymous said...

thanks for your help...it's very useful!

Anonymous said...

In IE you cannot change text property until the new OPTION element is added to a SELECT object.

Ronny said...

Thank you very much for this post!!

China travel said...

This is so much more than i needed!!! but will all come in use thanks!I am a china tour lover,You can learn more: Beijing tour| Lhasa Tour | Beijing tour packages

jaring futsal said...


The article posted was very informative and useful
thanks for sharing..
jaring futsal | jaring golf | jaring kassa / jaring polynet | jaring pengaman proyek | jaring pengaman bangunan | jaring pengaman gedung | jaring gawang | jaring paranet / jaring tanaman | rumput sintetis / rumput futsal |
tangga darurat | jaring cargo | agen jaring | jaring outbound | jaring truk | tali tambang
http://jaringfutsal.wordpress.com
http://jualjaringfutsal.wordpress.com
http://tokojaring.wordpress.com
http://jualtambangmurah.wordpress.com
http://pasangjaringfutsal.wordpress.com
http://pancasamudera.wordpress.com

squillman said...

11 years later, this is still relevant in the .NET WebBrowser control using the IE11 engine.... Works great outside of the WebBrowser control (that is, straight IE) but inside the control this still is an issue. Your post saved my code. Thank you!