views:

2258

answers:

3

the following js works fine in FF2 but in IE6 the dropdown always selects one option to early, IE -> testix2 vs. FF2 -> testix3 If we add an alertBox somewhere in the script, it also works fine in IE6. But how to solve this without an alertBox?

tia

<script language="JavaScript" type="text/javascript">
<!--
function Entry(value, name, selected) {
    this.value = value;
    this.name = name;
    this.selected = selected;
}


//-->
</script>
     <select id="selSeaShells">

     </select>
<script language="JavaScript" type="text/javascript">
<!--
var productCategoryLevel2 = new Array();

productCategoryLevel2.push(new Entry('Hallo1', 'testix1', false));
productCategoryLevel2.push(new Entry('Hallo2', 'testix2', false));
productCategoryLevel2.push(new Entry('Hallo3', 'testix3', true));

    var i = 0;
        for (i in productCategoryLevel2) {
     var optL2 = document.createElement('option');
     optL2.selected = true;

                optL2.text = productCategoryLevel2[i].name;
     optL2.value = productCategoryLevel2[i].value;
     if (productCategoryLevel2[i].selected == true) {
      productCategoryLevel2[i].selected = true;
      optL2.selected = true;
     } else {
      optL2.selected = false;  
     }
                try {
      document.getElementById("selSeaShells").add(optL2, null);
                } catch(ex3) {
      document.getElementById("selSeaShells").add(optL2);
                }
        }
//-->
</script>
+3  A: 

I'm not entirely sure why your example does not work, but it works if you do it like this (i.e. setting the selectedIndex on the <select> rather than setting the <option>'s selected propery). Tested FF3, IE6, Chrome.

var i = 0;
for (i in productCategoryLevel2) {
    var optL2 = document.createElement('option');

    optL2.text = productCategoryLevel2[i].name;
    optL2.value = productCategoryLevel2[i].value;
    try {
        document.getElementById("selSeaShells").add(optL2, null);
    } catch(ex3) {
            document.getElementById("selSeaShells").add(optL2);
    }

    if (productCategoryLevel2[i].selected == true) {
            document.getElementById("selSeaShells").selectedIndex = i;
    }      
}
Tom Haigh
Another weird IE6 bug solved.
Eduardo Molteni
A: 

I can't test this right now, but you may want to iterate over your array using a standard for(;;) loop rather than the for..in construct, which should only ever be used on objects in javascript.

Triptych
A: 

This feels like an IE bug (I wonder if it's a problem with converting a true to a 1), but you've brought it on by basing the select index on the options not the select itself which tomhaigh fixes.

Important to realise that if you start with zero options, it doesn't matter what value you'd like to give the first option for select - as element one of a set of one it can only be selected=true.

(I agree with triptych about the for too)

annakata