views:

137

answers:

2

My client asked me (a js 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 FF but fails in IE7 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 IE's beef with switching option items?

+1  A: 

Ah 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;
}
leeand00
+1  A: 

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:

  shippingLocation.options[0] = swap;

IE is complaining because you're 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>
Salty
Glad I could help =]
Salty