When you add OPTION elements to a SELECT box, and the SELECT element is contained in an element that is set to display: none by using the style attribute, the selected OPTION value may be lost.
↑ Back to the top
Internet Explorer is losing the selected OPTION value if that value is set before the options to the SELECT box are added.
↑ Back to the top
To avoid the problem, set your container element to display: none by using script instead of by using the style attribute of the element.
To work around this problem, set the select value after you add the OPTION element to the SELECT box.
↑ Back to the top
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.
↑ Back to the top
The following code demonstrates the failing and working code:
<HTML>
<HEAD>
<SCRIPT Language=JavaScript>
function populateSelects() {
populateProblem();
populateWorking();
div1.style.display = "Block";
}
function populateProblem(){
var oOption;
for (var x = 0; x < 3; x++) {
oOption = document.createElement("Option");
oOption.text = "Option " + x;
oOption.value = x;
// Setting selected before adding Option to select1 demonstrates problem.
if (x == 1) {
oOption.selected = true;
}
select1.add(oOption);
}
}
function populateWorking() {
var oOption;
for (var x = 0; x < 3; x++) {
oOption = document.createElement("Option");
oOption.text = "Option " + x;
oOption.value = x;
// Setting selected after adding Option to select1 resolves problem.
select2.add(oOption);
if (x == 1) {
oOption.selected = true;
}
}
}
</SCRIPT>
</HEAD>
<BODY onLoad="populateSelects();">
<DIV id="div1" style="Display: None;">
When the page loads, it creates the Option elements and adds them to the
Select tag. Both Select tags should have Option 1 selected. However, the
'Problem' Select is not set to Option 1 as we added the Option after the
selected value is set. This is the bug. In the working one, we set the
selected value after we add the option. In this case, it works fine.
Problem: <SELECT id="select1"></SELECT>
Working: <SELECT id="select2"></SELECT>
</DIV>
</BODY>
</HTML>
↑ Back to the top
For more information about developing Web-based solutions for Microsoft Internet Explorer, visit the following Microsoft Web sites:
↑ Back to the top