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 );