0

Why does this code work in IE, but not in Firefox?

elems = document.forms[0].getElementsByTagName("select");
for (i = 0; i < elems.length; i++) {
   if (elems[i].studentid && elems[i].studentid == studid && elems[i].selectedIndex == 0)
      elems[i].selectedIndex = 1;
}
Tariqulazam
  • 4,535
  • 1
  • 34
  • 42
Fandango68
  • 4,461
  • 4
  • 39
  • 74

1 Answers1

1

It would help greatly to see a relevant snippet of HTML.

In the code, it seems that elems[i] is a select element, and elems[i].studentid is an attempt to read a property named studentid. The related HTML might be like:

<select studentid="..." ...>

There is no standard HTML select element attribute called studentid, therefore even if that attribute has been added to the select element, it will not be available as a property in Firefox (and probably other browsers). Therefore the test fails at:

elems[i].studentid

where Firefox will return undefined, which evaluates to false. However, IE does add non–standard attributes as properties, so the test may pass in IE if the attribute has been set.

To access non–standard attributes the getAttribute method should be used for cross–browser compatibility, so the test might be:

elems[i].hasAttribute('studentid') && elems[i].getAttribute('studentid') == studid ... 

There doesn't seem to be any value in the hasAttribute test, so that can probably be dropped. Since elems[i] is used multiple times, I'd also store the result:

var elem = elems[i];
if (elem.getAttribute('studentid') == studid && elem.selectedIndex == 0) {
  elem.selectedIndex = 1;
}
RobG
  • 142,382
  • 31
  • 172
  • 209
  • I think your response actually answered it, but to answer your initial HTML request... <%# Eval("StudentFamilyName") %> – Fandango68 Mar 28 '13 at 05:03
  • ...What it's meant to do is look through a GridView column to match the student with the one clicked by the user, and toggle the dropdown in the row to the first element (index 1). This will reveal a value "Present". This is working in IE, but not in Firefox. I thought the problem was the elem.selectedIndex = 1. I tried changing it to jquery like code from other Google searches, but neither worked and in fact broke the entire thing because it would not work in IE either! But in relation to the "elems[i].studentid" is where I think the problem is. Firefox thinks "studentid" to be a keyword? – Fandango68 Mar 28 '13 at 05:08
  • Per my answer, Firefox does not make non–standard attributes available as properties so you have to use *getAttribute* to read them. Alternatively, use a standard attribute (e.g. [*class*](http://www.w3.org/html/wg/drafts/html/master/dom.html#classes) or more recently [*data-*](http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)) for such attribute values if you want to access them as properties. – RobG Mar 28 '13 at 06:17