Reputation: 411
Why does this work in ie8?
function testFunction(ctrl)
{
alert(ctrl.value);
}
I have a javascript function on my page like so. I then have a input tag with an id of "text1" and a button with the following onclick event
<input id="text1" value="value" />
<input type="submit" onclick="testFunction(text1)" value="Click" />
the javascript function does indeed alert the value of the textbox, but i am just passing in the id of the textbox, unquoted. I dont have to call getelementbyid, it just works. What is ie doing here, it doesnt work in firefox. How does the id turn into the actual textbox object, and i can call cntrl.value on it?
P.S. - I know I shouldn't user the onclick handler in this way, just an easy way to illustrate the issue.
Thanks
Upvotes: 0
Views: 232
Reputation: 25445
Following on from gonchuki answer. This is how your should be doing it.
function testFunction(ctrl)
{
var obj = document.getElementById(ctrl);
alert(obj.value);
}
<input type="submit" onclick="testFunction('text1')" value="Click" />
Also there is nothing wrong with using the onclick event of a button. That is what it is there for.
Hope this helps.
Upvotes: 0
Reputation: 7131
The ctrl.value
syntax is used for a HTML element with the name
attribute set to "ctrl". It is not standard that it is used for id
. You have to use getElementById
for cross-browser support.
Upvotes: 0
Reputation: 4134
This is a side effect of your page probably being on quirks mode and IE doing nasty DOM Level 0 stuff.
The actual explanation is that on DOM Level 0 elements with an ID get automagically added to the window
global object, and in consequence automagic variables are getting created on the global scope that point towards your DOM element.
Long story short: don't code like that, ever. You are relying on a 'de-facto' standard where browsers usually try to imitate what the other does, and this is a case where IE behaves really bad and other browsers didn't follow suit. Use actual DOM methods where suitable, like getElementById
in this case.
Upvotes: 8