August 3, 2000 - Using "this" in Event Handling | WebReference

August 3, 2000 - Using "this" in Event Handling

Yehuda Shiran August 3, 2000
Using "this" in Event Handling
Tips: August 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

When you call a function via an event handler, you may refer to the form element which triggered the event handler, such as a text field or a button. Every form element is an object. You can use the keyword this to refer to the "current" object. The following entry field initially displays the string "email..." but changes to "thank you" once you modify it (click outside the field to signal the change's end):

There are two ways to implement this effect, with and without this. The following script refers to a form element without using the this keyword (this script was used for the field above):

<SCRIPT LANGUAGE="JavaScript">
<!--
function process1() {
  document.forms[0].elements[0].value = "thank you";
}
// -->
</SCRIPT>
<FORM>
<INPUT TYPE="text" NAME="myField" VALUE="email..." onChange="process1()">
</FORM>

We can implement the same effect with the this keyword. Convince yourself that the effect is the same:

Here is the script:

<SCRIPT LANGUAGE="JavaScript">
<!--
function process2(callingElement) {
  callingElement.value = "thank you";
}
// -->
</SCRIPT>
<FORM>
<INPUT TYPE="text" NAME="myField" VALUE="email..." onChange="process2(this)">
</FORM>

This form is preferred because you can change the element's position, name, or any other optional attribute (other than the event handler) and the script will still work without modifications. The keyword this refers to the element providing the event handler. In this case, the value of this is equal to document.forms[0].elements[0]. When the function process() is called, the value assigned to the callingElement parameter is this, so callingParameter.value is equivalent to document.forms[0].elements[0].value.