Friday, August 19, 2005

Name == ID?

Someone please explain how this works in Internet Explorer? Firefox works as expected, but Internet Explorer happily goes on just like the hidden input actually has its ID property set.


<html>
<script language=javascript>
function foo() {
alert(document.getElementById('testElement').value);
}
</script>
<body>
    <input type='hidden' name='testElement' value='stacey'>
    <input type='button' onclick='foo();' text='push me' value='push me'>
</body>
</html>

2 comments:

MegaManJuno said...

Perhaps if there's nno ID set, but you set the Nam property, it defaults the ID to match the name...?

I ran into a somewhat similar issue the other day. I was working on something to hide/show a section of the page (div) depending on when a user clicks one of 2 specific links with javacript functions on the onclick event. Now if you set a Name property on the div, IE happily hides and shows it fine. Opera, however did not (which is the proper behavior I believe since I think I found that divs don't have a name property under the standards). I didn't check it in FireFox, but I'm guessing it would have worked similar to Opera (most things do). I ended up doing a get ElementsByClassName and it works fine in both now.

Stacey said...

The annoying part is that the control in the code behind has an ID property that corresponds to the name in this case. Yet on other controls it has both a name and an ID property, and they are definitely different. It's this "consisentcy" that drives me nuts. I ended up in the code behind changing the script that I generated to find the registered hidden field to use the getElementsByName() method instead of the getElementById() method, and referencing the 0th element since I knew there would only ever be one. Annoying, but it works in both cases.