Creating Form objects

Like frames, the form elements in your JavaScripts must be able to identify themselves to other parts of your program. Generally, form elements include a name attribute that can be used to label the object. For example, a checkbox element can be created with the name 'cb1' using the following code:

<input type="checkbox" name="cb1">This is a checkbox

Naming form elements becomes especially important when a function needs to process different elements of the form. Using the checkbox definition above, a function would be able to determine whether the checkbox had been selected like this:

function isChecked(form) 
{
if(form.cb1.checked == true)
	alert("cb1 is checked!);
else
	alert("cb1 is not checked);
}

As with frames, the name of a form element can be referenced using its name as a property of the Form object. You might have noticed that there's a parameter to the function called 'form', and then the 'cb1' element is referenced as a property of that object (form.cb1). It is often much easier to send a reference to the Form object to functions, and then refer to specific elements as properties of that reference. For example, to use the function in the example above, we could invoke it using a button created with the following syntax:

<input type="button" value="cb1 check" onClick="isChecked(this.form)">

The 'this' keyword is new, and may be a little confusing. For now, just remember that by sending 'this.form' as an argument to a function, you are referring to the current form. The 'this' keyword will be discussed in greater detail next month.