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:
- keyword "this" is referenced from inside a form or form element tag
- when used with the word, "form", as in "this.form", it is a reference to the form object. used from within both a form tag and a form element tag, "this.form" can be used instead of the entire path to the form, "document.formname" reference.
- when used in a form element, it is a reference to that form element object, and can be used instead of the entire path, "document.formObject.elementObject"
- any property that would otherwise be appended to the document object path reference may also be appended to it, e.g. "this.value" is the same as, "document.formObject.elementObject.value
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
<option> http://www.jennifermadden.com
<option> http://www.builder.com
<option> http://www.dansteinman.com
</select>
And there you have it - a JavaScript powered select menu in one short snippet. What could be easier?
View the Source