Rearranging options in Internet Explorer?

My client asked me (a JavaScript client side programmer) to change the order of the options so that their company parameter appears at the top of the select box on page load.

The following code works in Firefox but doesn't work 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 am getting an error next to the third line from the bottom:

shippingLocation.options[0] = swap;

      

The error indicates that "the object does not support this property or method."

What is Internet Explorer beef with toggle options?

+1


source to share


2 answers


Well, I tested a bit and I believe IE considers the parameter array to be immutable (in some way). You can edit parameters and they can be deleted, but you cannot set one parameter to another.

So when you do this:

  shippingLocation.options[0] = swap;

      

IE is complaining because you are trying to set one option to another.



I would do this instead:

> Removed due to excessive stupidity on
> my part. :P

      

Here's a better way:

<script type="text/javascript">
function swap(obj,i,j) {
    sib=obj.options[i].nextSibling;
    obj.insertBefore(obj.options[i],obj.options[j]);
    obj.insertBefore(obj.options[j],sib);
}
</script>

      

+1


source


And here we go. Much more elegant than the code above.



function swapOptions(obj,i,j){
    var o = obj.options;
    var i_selected = o[i].selected;
    var j_selected = o[j].selected;
    var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
        var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
    o[i] = temp2;o[j] = temp;o[i].selected = j_selected;o[j].selected = i_selected;
}

      

+1


source







All Articles