The this Keyword and Forms

The function in the previous example contained an argument that acted as a generic representation of multiple form element objects. This allowed a single function to perform the same task on different objects, eliminating the need for multiple functions.

The this keyword is also a generic reference to an object, and provides a shorthand reference to both form objects and element objects.

Here are the basic rules governing the use of the this keyword within a form:
<form name="MyForm" onsubmit="alert(;return false">
<input type="radio" name="MyRadio" onClick="alert(">
check to alert this object's name

<input type="text" name="MyText">
Enter some text in this field then check the following radio to alert your entry

<input type="radio" name="MySecondRadio" onClick="alert(this.form.MyText.value)">
Check this to alert text field's value

<input type="checkbox" name="MyCheckbox" onClick="alert(this.checked)">
check and uncheck to see boolean value of this object's checked property

<input type="submit">
see onsubmit event handler in opening form tag for action taken when submit is clicked
The Winner of the Best Use for This
The this keyword is also useful for referencing forms contained in layers when coding for NN4.x, but the best place to use the this keyword for reference simplification is when you have to script for a select menu. To fully appreciate just how much coding is saved, see select menu object lessons first. Here it is:

<select onchange="location=this.options[this.selectedIndex].text">
   <option> Make A Selection
And there you have it - a JavaScript powered select menu in one short snippet. What could be easier?

View the Source


View Source | Home | Contact