My client asked me (a JavaScript client-side programmer) to change the order of the options so that their company’s option appears at the top of a select box when the page loads.
The following code works in Firefox but fails in Internet Explorer 7 when I try to swap two options:
function load{ var shippingLocation = document.getElementById('location'); var swap = null; var initiallyFirstItem = shippingLocation.options[0].cloneNode(true); var lastPos = null; for(var i = 0; i < shippingLocation.length; i++) { if(shippingLocation.options[i].value == 'XETEX') { swap = shippingLocation.options[i]; lastPos = i; break; } } console.debug('sl: ' + shippingLocation.options[0]); console.debug('s: ' + swap); shippingLocation.options[0] = swap; shippingLocation.options[lastPos] = initiallyFirstItem; shippingLocation.selectedIndex = 0; }
I get an error on the next to the third line from the bottom:
shippingLocation.options[0] = swap;
The error states that ‘object doesn’t support this property or method’.
What’s Internet Explorer’s beef with switching option items?
Well, I did some testing and I believe that IE considers the options array as immutable (in a way). You can edit the options and you can remove them but you can’t set one option to another.
So when you do this:
IE is complaining because you’re trying to set one option to another.
I would do this instead:
Here’s a better way: