The following code is on http://www.0011.com/test_js/test_without_this.html the first input field uses alert(value) instead of alert(this.value) and it works. the second and third input fields do not use the "inline anonymous function" but use another anonymous function... but the second one will show the value while the third one won't. I thought inline anonymous function is the same as assigning element.onclick= function() { whatever there was } isn't it? If so why would the first input field work and the third doesn't? It is true in IE 7, Firefox 3, and Safari 3. Many thanks! <form> <input id="text1" type="text" value="wah ha ha 1" onclick="alert(value)"> <input id="text2" type="text" value="wah ha ha 2"> <input id="text3" type="text" value="wah ha ha 3"> </form> <script> document.getElementById("text2").onclick = function() { alert(this.value) } document.getElementById("text3").onclick = function() { alert(value) } </script> HTML:
Go with what works and don't waste your time with the rest...or complicate things more by using document.form as well.
The last one won't work cause it uses value from the global scope, not the value of the unput field. When creating an anonymous function you should always use this to make sure that the right object is used. Not using this will cause looking for the variable in the global scope as if you have used window.value.
And it's generally good form with JS to avoid or reduce confusion with global variables. I'd rather set all my variables in functions, and then use window.whatever when I need to use a variable in multiple functions. Global variables weren't ever good ideas-- esp when you're combining multiple javascripts on a single page and they happen to use the same variable names for different things! You might want to check out Crackford's book: "Javascript: the good parts".