Javascript getElementByID strangeness?

By chris ·
Does anyone have experience with Javascript to provide an answer to this simple code issue?

Why does getElementByID not work in my case with Opera and Firebox but it does with IE?? I thought this method was cross browser compatible.

My test alerts simply do not fire in Opera or Firefox which results in the rest of my validation code failing too.

I'm calling this function from the onChange event on a field within a form.

Can anyone shed any light on this as it's baffling me!

strCtrl can be name of any field which I want to validate

function validate_ctrl(strCtrl)
if (strCtrl=='Name') {

// get handle on control
var ctrl = document.getElementById(strCtrl);
alert("Test"); // this fires in IE 7, Opera9.6, Firefox3.6
alert(ctrl.value); // this fires only in IE 7! Why???

//due to this none of the follow will work in Opera or Firefox?
// validate control
if (ctrl.value.length > 3) {
//color TD BG green
document.getElementById("Step1").style.backgroundColor = '#009900';
} else {
// not valid so color TD BG grey
document.getElementById("Step1").style.backgroundColor = '#999999';
//validate other controls here
//etc etc

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Answers

Collapse -

IE and ID's versus names

by robo_dev In reply to Javascript getElementByID ...

Firefox supports document.getElementById() but its looking for id and not name.

IE thinks a name is the same as an id but it also understands document.all, if that's being used, in which case it will use the name.

I hate to admit that IE is better that FF in this case, but it is.

Collapse -

Your right!

by chris In reply to IE and ID's versus names

Many thanks. The ID issue was part of the problem. Another reason was that some controls were named incorrectly due to case.
i.e. Name instead of name or vice versa.

With both of these clarified and sorted it's now working.

Thanks again!

Related Discussions

Related Forums