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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

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.


People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger