View Full Version : 'this' object in form elements

10-22-2005, 08:01 AM

I have seen some code around the place using the 'this' object differently to what I've seen in tutorials/references around the place.

I've read that 'this' points to the current window object, but I've also seen people doing this:

<input type="input" name="foo" onchange="setValue(this);">

Is this correct? When used in that context does the this object point at the input 'foo'?

Philip M
10-22-2005, 08:48 AM
Yes indeed. The object foo and its value is passed to the function setValue(), e.g.

function setValue(which) {
var theValue = which.value;
theValue ++ // or whatever

10-22-2005, 08:49 AM
Thanks for that :) Makes my page much simpler to code and understand.

10-24-2005, 02:35 PM
FYI: This (no pun intended) is very helpful when you have several <input>s that call the same function. For example you can type onClick="myFunction(this.type, this.name)" and then just copy-paste into each <input> field that would use that function...