Linking Javascript Objects with HTML Controls


Steven Disbrow is the owner of EGO Systems, a computer consulting firm in Chattanooga, TN. In the past, he has worked as a freelance programmer, Webmaster, editor, writer, and technical instructor. His most recent achievement was the creation of the Advance Shipping Notice Web site for the Tennessee Valley Authority. He can be contacted at [email protected].

LAST TIME1, I discussed how to create new objects with JavaScript. However, the objects we looked at were abstract objects with no ties to the Web browser. This time, we'll review how to integrate your JavaScript objects with the controls on your Web pages. But before we can do that, we need to look at those HTML controls and see how they themselves can be treated as objects.

Because JavaScript's main purpose is to enhance Web pages, it should be no surprise that most of the elements of those pages, and of the Web browser itself, are accessible from JavaScript as objects. In fact, almost every browser and Web page element has a corresponding JavaScript object. These objects allow you to directly manipulate the browser and the Web page that it loads.

The "window" object is a built-in JavaScript object that represents the entire browser window. The window object contains various properties, methods, and objects that give you access to and control of almost every element of the Web browser. While by no means a complete list, the following shows some of the more useful properties, methods, and objects that belong to the window object:

  1. document object—This object represents the HTML file that is loaded into the browser at this moment. This object contains all of the forms, controls, etc., that you will use to interact with users.
  2. history object—This JavaScript object contains a list of all URLs that you have visited since starting the Web browser. You can use the "history.back()," "history.forward()," and "history.go(n)" methods to move through this list.
  3. setTimeout method—This method allows you to queue up a JavaScript statement for execution at a later time.
  4. open method—This method lets you open a new browser window and load an HTML file into it.
THE document OBJECT
The "document" object is probably the object that you will work with the most. It represents the Web page that is loaded in the browser and contains all of the elements (forms, controls, links, etc.) that you will use to interact with users. Here is a list of some of the more useful objects and methods in the document object:
  1. write method—This lets you write a string out to the Web browser. This string can contain static text, JavaScript variables, or even HTML codes! (Note, however, that this method works properly only when the page is being loaded.)
  2. cookie property—This property represents the cookie that is associated with this document.
  3. location object—This object holds the URL of this document. By assigning a URL to the "href" property of this object, you can cause a new Web page to be loaded.
  4. form object—This object is used to represent a single form (i.e., a set of "form><>/form>" tags) on the Web page. This object contains each of the objects that represent the controls on that form. (See the discussion of the form object that follows.)
  5. forms array—This is an array of all of the form objects for this page.
The "form" object is the object that contains all of the actual controls (check boxes, buttons, etc.) that you use to interact with the user. The "forms" array is an array that holds all of the form objects on the page. Here are some of the important properties and methods of a form object and the forms array:
  1. length property—This property of the forms array tells you how many individual forms are on this page.
  2. submit method—Submits a form just as if the user had clicked a "Submit" button.
  3. reset method—Resets a form just as if the user had clicked a "Reset" button.
  4. "control" objects—A separate control object (each with its own properties) will be created for every "input>," " select>," and "textarea>" tag that you define between your "form><>/form>" tags.
As mentioned, for every control defined inside a form on your Web page, a corresponding JavaScript object is created when the Web page is loaded. Those objects, and their corresponding HTML tags are:
  1. select object—A "select" object represents the pop-up menu that is created by a "select>" tag and its "option>" tags. The options (i.e., the menu items) are held in an array, called "options" inside the select object.
  2. check box object—Created by an "input type=checkbox>" tag.
  3. radio button object—Created by one or more "input type=radio name=rName>" tags. This object represents all the radio buttons with the same name in this form.
  4. text object—Created by an "input type=text>" tag.
  5. textarea object—Almost exactly the same as a text object, this is created by a set of "textarea>/textarea>" tags.
  6. button objects—Created by "input type= button>," "input type=submit>," and "input type=reset>" tags.
Take a look at the block of HTML code shown in Listing 1. When loaded into a JavaScript-capable browser, this code will create five JavaScript objects:
  1. A document object. This represents the entire HTML file.
  2. A form object with the JavaScript name "form1."
  3. A text object with the JavaScript name "text1."
  4. A check box object with the JavaScript name "checkbox1."
  5. A button object with the JavaScript name "button1."
Notice in the example that we've given each element on our page a "name=" attribute. The names we specify here are the names that JavaScript will use to name the objects it creates for these HTML elements. For this reason, it is very important that you give all of your HTML controls and forms names! These names will allow you to quickly and easily access your HTML elements from your JavaScript code.
Important Note: The names you give to your HTML controls and forms must be legal JavaScript variable names! This means no spaces, and the names must start with an alphabetic character or underscore! Also, when you try to use these names from JavaScript, they will be case-sensitive!

At this point, you should see the hierarchy of the JavaScript objects on the Web page. If you are thinking ahead, you may already realize how to use this hierarchy to get to the object you want. But, in case you don't, here's an example.

A text object has a property called "value." This "value" property contains the actual text that is displayed in the text box. So, if we wanted to get the text out of our "text1" text box (which we defined in Listing 1) and put it in a variable called "theText", we would code:

theText = document.form1.text1.value;

Notice that, in order to get to the value, we proceed from the largest object (the document object) down to the smallest (the text object).

Now that we know how to define our own JavaScript objects and how JavaScript creates objects for HTML elements, the question is, how do we tie the HTML-derived objects to our custom-made JavaScript objects?

The answer is, event handlers. Almost all HTML controls have the ability to receive events from the Web browser and call a JavaScript function in response. All we need to do is plug our objects into the appropriate event handler and the rest will happen automatically. For example, let's take the simple object we created in our last installment ("anObject") and tie it to an HTML button. The code to do this is shown in Listing 2.

The part we are interested in here is the "input>" tag. Notice the "onClick" handler? It's telling the browser that, when the user clicks on this button, it should call the "sayHello" method of the object named "myObj." That's all there is to it!

Now that we can link JavaScript objects to HTML controls, let's look at a more complex task: using JavaScript to make HTML controls easier to use. For this, let us consider the lowly check box. HTML check boxes are rather simple things, but it can still be a pain to manage a large number of them. By creating a JavaScript check box object, we can use the same code to manage any number of HTML check boxes.

The JavaScript code for a check box object is rather simple. The constructor is shown in Listing 3. As expected, this isn't an overly complicated object. It has two instance variables and three methods.

THE "form" AND "name" VARIABLES
To truly "link" a JavaScript object to an HTML control, you must be able to access that control from your JavaScript code. To do that, you have to know two things about the control: the name of the HTML form it is in and the name of the HTML control itself. The "form" and "name" instance variables allow us to keep track of this information for each control. (We've looked at this concept before.2)

Once we have this information, we use it to access our control by using JavaScript's "eval" method.

The eval method takes a string representing a valid JavaScript statement and executes it as if it had been hard-coded in your HTML file. So, for example, the statement:

eval( "alert( 'Hello World!')");

will display an alert window with the string "Hello World!" in it, just as if you had coded:

alert( 'Hello World!')

By keeping the name of our form and the name of our control inside our object, we can create statements that, when passed to the eval method, let us access our HTML control. For example, in the code we will look at in a moment, our form is named "oCheckBoxExample," and our first check box control is named "testBox1." Inside the "oCheckBoxIsChecked" method, you will see the line of code:

eval( 'checked = document.' + this.form + '.' + + '.checked;');
When the JavaScript interpreter reaches this line of code, it will first build the string inside the parentheses. The resulting string will give us an eval call that looks like this:
eval( 'checked = 
The eval method will then pass this string to the JavaScript interpreter, which will execute it as if it had been hard-coded directly in the HTML file.

Listing 4 shows all the source code needed to implement and test our check box object. The methods of the oCheckBox object are:
  • oCheckBoxIsChecked—This method merely looks at the "checked" property of the check box and returns it.
  • oCheckBoxTurnOn and oCheckBoxTurnOff—These methods are even simpler. We simply set the "checked" property of the box to whatever is desired.
As you can see, this is a very simple object, but we can easily reuse it to manage as many check boxes as are needed.

Of course, check boxes are very simple controls, and they don't usually need much "managing." But, this simple example should already have you thinking about how to use this same technique to enhance other HTML controls. So, next time, we'll look at how to use this technique to give new features (like data validation) to other HTML controls.

1. Disbrow, S., "Your own private Idaho()," Java Report, Vol. 4, No. 4, Apr. 1999, pp. 66-69.
2. Disbrow, S., "Using eval to generate and execute JavaScript," Java Report, Vol. 3, No. 4, Apr. 1998, pp. 76-78.

Quantity reprints of this article can be purchased by phone: 717.560.2001, ext.39 or by email: [email protected].

About the Author

Steven Disbrow is the owner of EGO Systems, a computer consulting firm in Chattanooga, TN. He can be contacted at [email protected].