Archive for March 27, 2008

Javascript gripe # 2

0
share
 

The add() function of the html select object functions totally different in IE and Firefox.

It is defined as :
selectObject.add(option,before)

Where option is an option object. Before is the tricky part.

In firefox, the second parameter is supposed to be a reference to the option object you want to place your new object in front of. In IE, it is the index to the object you want to remove.

These are fundamentally different.

In FF, you have to do this:
boxRef.add(newOpt,boxRef.options[i]);

in IE, you do this:
boxRef.add(newOpt,i);

Apparently, Firefox is correct according to the DOM specifications:
void add(in HTMLElement element, in HTMLElement before) raises(DOMException);
void remove(in long index);

But tell me, why does the add method use an object while the remove uses an index???. The standard is messed up, not IE.

Anyway…

Javascript tip

0
share
 

I was having the most unusual problem in a function that used a for loop to find selected items in a html select list. My iterator variable “i” was for some reasen ending up with a value higher than the for loop would allow.

As it turns out, if you declare a variable without using the “var” keyword, that variable has global scope.

Case in point:

function pressRemove() {
  fromBox = selBox;
  toBox = allBox;
  for (i=fromBox.length-1;i>=0;i--) {
    if (fromBox.options[i].selected) {
	  addOpt(toBox,fromBox.options[i].value,fromBox.options[i].text,2);
	  fromBox.remove(i);
	}
  }
}

The function addOpt includes it’s own for loop, also using a variable named i. That inner for loop was overwriting the value in this for loop!

...
  for (var i=fromBox.length-1;i>=0;i--) {
...

By changing all the for loops to declare their variables, the problem was solved. Personally, I think that is a really stupid “feature”, but since both IE and Firefox do it, it is expected.

Go to Top