elements, which you will study next. As with other form elements that create controls, the <select> element must appear within a block-level element such as the element. The selection list can appear as an actual list of choices or as a drop-down menu. Depending on the number of options in the list, a selection list can also include a scroll bar. Table 5-8 lists the attributes of the <select> element.
Creating Selection Lists Attribute
Description
disabled
Disables the selection list
multiple
Specifies whether a user can select more than one option from the list; a Boolean attribute
name
Designates a name for the selection list
size
Determines how many lines of the selection list appear
Table 5-8
Attributes of the <select> element
Like other form controls, the <select> element includes a name attribute that is submitted to a Web server. However, the value portion of a <select> element’s name=value pair is the value assigned to an option that is created with the element (which you study next). If a <select> element includes the Boolean multiple attribute, which specifies whether a user can select more than one option from the list, and a visitor selects more than one option in the list, then multiple name=value pairs for the <select> element are submitted with the form. Each instance of a <select> element’s name=value pair includes a value assigned to one of the selected list options created with the element. The size attribute designates how many lines of the selection list appear when the form is rendered in a Web browser. If this attribute is excluded or set to 1, and the <select> element does not include the multiple attribute, then the selection list is a drop-down style menu. For drop-down style menus, the first option element is automatically selected.
Menu Options You use elements to specify the options that appear in a selection list. The content of an element appears as a menu option in a selection list. Table 5-9 lists the attributes of the element. Attribute
Description
disabled
Disables the option
label
Designates alternate text to display in the selection list for an individual option
selected
Determines if an option is initially selected in the selection list when the form first loads; a Boolean attribute
value
Specifies the value submitted to a Web server
Table 5-9
Attributes of the element
277
CHAPTER 5
278
Validating Form Data with JavaScript
You specify a selection list’s menu options using elements placed within a <select> element. Each selection list must contain at least one element. For example, the following code creates two selection lists. Figure 5-14 shows the code in a Web browser. Notice that because the first list’s <select> element includes the multiple attribute, you can select multiple options, as shown in the figure. Also notice that “All” is the selected value in the first list and the “$2,000 to $2,999” option is the selected value in the second list. Central Valley Appliances Televisions
Creating Selection Lists
279
Figure 5-14
Two selection lists
Next, you add a selection list to the subscription.html document that a subscriber uses to select his or her job title. To add a selection list to the subscription.html document: 1.
Return to the subscription.html document in your text editor.
2.
Add the following selection list above the paragraph that contains the submit and reset buttons: What is your job title?
<select name = "jobTitle"> IT staff Technical consultant Systems integrator Manager Director Vice President CIO, CTO, CSO, CEO, COO, Chairman, President Other
3.
Save the subscription.html document, and then open it in your Web browser. You should see the selection list at the bottom of the page. Because you did not include size and multiple attributes in the <select> element, the selection list appears as a drop-down menu.
4.
Close your Web browser window.
CHAPTER 5
Validating Form Data with JavaScript
The Select and Option Objects
280
The Select object represents a selection list in a form. The Select object includes an options[] array containing an Option object for each element in the selection list. The Option object represents an option in a selection list. You use the Select and Option objects with JavaScript to manipulate the options displayed in a selection. The Select object contains the properties listed in Table 5-10 and the methods listed in Table 5-11.
Property
Description
disabled
Sets or returns a Boolean value that determines whether a control is disabled
form
Returns a reference to the form that contains the control
length
Returns the number of elements in the options[] array
multiple
Sets or returns a Boolean value that determines whether multiple options can be selected in a selection list
name
Sets or returns the value assigned to the element’s name attribute
options[]
Returns an array of the options in a selection list
selectedIndex
Returns a number representing the element number in the options[] array of the first option selected in a selection list; returns -1 if No option is selected
size
Sets or returns the number of options to display
tabIndex
Sets or returns a control’s position in the tab order
type
Returns the type of selection list; returns “select-one” if the <select> element does not include the multiple attribute, or it returns “select-multiple” if the <select> element does include the multiple attribute
Table 5-10
Properties of the Select object
Method
Description
add(element, before)
Adds a new option to a selection list
blur()
Removes focus from a form control
focus()
Changes focus to a form control
remove(index)
Removes an option from a selection list
Table 5-11
Methods of the Select object
Creating Selection Lists
You append the properties in Table 5-10 to the name representing the <select> element. For example, for the selection list you saw earlier with a name attribute of “brand”, you use the following statement to assign the number of elements in the selection list to a variable named numItems: var numItems = document.forms[0].brand.length;
Similarly, the following statement assigns the currently selected option in the selection list to a variable named curSelection: var curSelection = document.forms[0].brand.selectedIndex;
If the size attribute is excluded or set to 1, and the <select> element does not include the multiple attribute, then the selection list is a drop-down style menu. For drop-down style menus, the first option element is automatically selected. However, for <select> elements that assign a value greater than 1 to the size attribute or that include the multiple attribute, to determine whether an option is selected in a selection list, you need to test whether the selectedIndex property contains a value of -1. If it does, then no option is selected. For example, the following code tests whether an option is selected in the brand selection list: if (document.forms[0].brand.selectedIndex == −1) window.alert("No option is selected."); else window.alert("An option is selected.");
The Option object contains the properties listed in Table 5-12. Property
Description
defaultSelected
Returns a Boolean value that determines whether the element representing the currently selected item includes the selected attribute
disabled
Sets or returns a Boolean value that determines whether a control is disabled
form
Returns a reference to the form that contains the control
index
Returns a number representing the element number within the options[] array
label
Sets or returns alternate text to display for the option in the selection list
selected
Sets or returns a Boolean value that determines whether an option is selected
Table 5-12
Properties of the Option object (continues)
281
CHAPTER 5
Validating Form Data with JavaScript (continued)
282
Property
Description
text
Sets or returns the text displayed for the option in the selection list
value
Sets or returns the text that is assigned to the element’s value attribute; this is the value that is submitted to the server
Table 5-12
Properties of the Option object
You append the properties in Table 5-12 to the options[] array. For example, the following code tests whether the first element in the options[] array for the brand selection list is selected: The Option objects do not contain methods.
if (document.forms[0].brand.options[0].selected == true) window.alert("The first option is selected."); else window.alert("The first option is not selected.");
Adding Options to a Selection List Although the current ECMAScript recommendations suggest using the add() method of the Select object to add new options to a selection list, this method is not consistently implemented in current Web browsers. For instance, according to the ECMAScript recommendations, you should be able to add a new option to the end of a selection list by passing a value of null as the second parameter of the add() method. While this works in Firefox 2.0, it will not work in Internet Explorer 7.0 unless you eliminate the second parameter altogether from the function call. Similarly, you should be able to pass an integer as the second parameter to indicate which element the new element should be added before. Conversely, while this works in Internet Explorer 7.0, it does not appear to work in Firefox 2.0. Until this method is consistently available, you should avoid using it to add a new option to a selection list. Instead, to add a new option to a selection list after a Web page renders it, you must create a new option with the Option() constructor. Creating a new option with the Option() constructor is similar to creating an array with the Array() constructor. The syntax for the Option() constructor is as follows: var variable_name = new Option(text, value, defaultSelected, selected);
Notice that the arguments passed to the Option() constructor match several of the properties of the Option object listed in Table 5-12.
Creating Selection Lists
The arguments allow you to set the properties of the new option in a single statement. For example, the following statement declares a new option and assigns values to each of the properties of the Option object: var gardeningItem = new Option("mulch", "mulch", false, false);
The preceding statement creates a new Option object represented by the gardeningItem variable, and assigns values to the object’s properties. You can also assign values to the properties after the new Option object is created. The following code performs the same tasks as the preceding statement: var gardeningItem = new Option(); gardeningItem.text = "mulch"; gardeningItem.value = "mulch";
After you create a new Option object and assign values to its properties, you assign the object to an empty element in an options[] array. For example, to assign the Option object created in the preceding code to the third element in an options[] array in a selection list named gardeningList, you use the following statement: document.forms[0].gardeningList.options[2] = gardeningItem;
Next, you add code to the subscription.html document that allows subscribers to build a selection of the technology journals to which they are currently subscribed. To add code to the subscription.html document that allows subscribers to build a selection of the technology journals to which they are currently subscribed: 1.
Return to the subscription.html document in your text editor.
2.
Add the following elements above the paragraph that contains the submit and reset buttons. The first element is a text box where users can enter the name of a journal to which they subscribe. Note that the text box does not include a name argument; this prevents the field value from being submitted along with the rest of the form data. The Add Journal button includes an onclick event handler that calls a function named addJournal(), which you will add next. In order for the document to be well formed, the <select> element must include at least one element. Therefore, you add a single element that displays “Enter the technologies journals you subscribe to” in the selection list. In the next section, you will add code to the addJournal() function that deletes this unnecessary element when the subscriber adds a journal to the selection list.
283 You do not have to assign values to all of the properties of a new Option object; you only need to assign values to the properties you need.
CHAPTER 5
Validating Form Data with JavaScript Journal
<select name = "journals" multiple = "multiple" size = "10" style = "width: 500px"> Enter the technologies journals you subscribe to
284 3.
Add the following addJournal() function to the end of the script section. Notice that the code uses the elements[] array to refer to the text box where users enter the names of journals to which they subscribe; this is necessary because the text box does not include a name argument. (Again, the lack of the name argument prevents the contents of the text box from being submitted with the other form data.) Also notice how the function determines where to add the new item in the options[] array. The number of items in the options[] array is retrieved using the Select object’s length property and assigned to a variable named nextItem. The value assigned to the nextItem variable represents the number of elements in the array. As you’ll recall, the length of the array is one more than the number of elements in the array (because the array begins with an element of 0). That means you can use the value to identify the next available element. function addJournal() { if (document.forms[0].elements[31].value == "") window.alert("You must enter a journal name."); else { var journal = new Option(); journal.text = document.forms[0] .elements[31].value; journal.value = document.forms[0] .elements[31].value; nextItem = document.forms[0].journals.length; document.forms[0].journals.options[nextItem] = journal; document.forms[0].elements[31].value = ""; } }
4.
Save the subscription.html document, and then open it in your Web browser. Scroll to the end of the Web page and try adding some journals to the journal list. One problem you may notice is that the “Enter the journals you subscribe to” option remains in the selection list after the user adds journals. You will fix this in the next section.
5.
Close your Web browser window.
Creating Selection Lists
Removing Options from a Selection List To remove a single option from a selection list, you pass the option’s index number in the options[] array to the remove() method of the Select object. For example, use the following statement to remove the first element in the options[] array of the gardeningList selection list. document.forms[0].gardeningList.remove(0);
When you remove an element from the options[] array using a statement similar to the preceding statement, the remaining elements are reordered. In other words, all of the element numbers following the deleted element are decreased by a value of one. You can remove all the options from an options array by appending the Selection object’s length property to the options[] array without the brackets, and then by assigning the length property a value of 0. For example, to remove all the options in the options[] array of the gardeningList selection list, you use the following statement: document.forms[0].gardeningList.options.length = 0;
Next, you add code to the subscription.html document that deletes journal names from the selection list. To add code to the subscription.html document that deletes journal names from the selection list: 1.
Return to the subscription.html document in your text editor.
2.
Add the following elements to the end of the element that contains the Add Journal button. The Delete Journal button includes an onclick event handler, which calls a function named deleteJournal(). You will add this function next. To the onclick event handler in the Clear List button, you will assign a statement that deletes all the items in the list.
3.
Add the following deleteJournal() function to the end of the script section. The function is very familiar to the deleteItem() function you saw in the shopping list form. function deleteJournal() { var selectedItem = document.forms[0].journals.selectedIndex;
285
CHAPTER 5
Validating Form Data with JavaScript if (selectedItem == −1) window.alert("You must select a journal name in the list."); else document.forms[0].journals .remove(selectedItem); }
286 4.
Finally, add the following if statement to the beginning of the else statement in the addJournal() function. This statement deletes the “Enter the technologies journals you subscribe to” option that is displayed by default in the selection list. if (document.forms[0].journals.options[0] && document.forms[0].journals .options[0].value == "none") document.forms[0].journals.options[0] = null;
5.
Save the subscription.html document, and then open it in your Web browser. Scroll to the end of the Web page and try adding some journals to the journal list. After you add the first journal, “Enter the technologies journals you subscribe to” should be removed from the list. Also, test the Delete Journal and Clear List buttons.
6.
Close your Web browser window.
Changing Options in a Selection List To change an option in a selection list, you simply assign new values to the option’s value and text properties. For example, use the following statements to change the value of the first option in the gardeningList selection list from “Pruners” to “Mulch”: document.forms[0].gardeningList.options[0].value = "Mulch"; document.forms[0].gardeningList.options[0].text = "Mulch";
The following shows a completed example of the shopping list to which you can add new items. An Add Item button in the form calls a function named addItem(), which adds new items to the selection list. A new Option object named gardeningItem is created, and its text and value properties are assigned the value of the first text box in the form. A function named deleteItem(), which is called from the Delete Item button, handles deleting single items from the list. The onclick event handler in the Clear List button is assigned a statement that deletes all of the items in the list. A function named changeItem() changes the value of a selected item in the list to the value in the New Item text box. Figure 5-15 shows how the form appears in a Web browser.
Creating Selection Lists <script type = "text/javascript"> /* */
Spring Planting Gardening List
Figure 5-15
Shopping list form
Creating Selection Lists
Next, you add code to the subscription.html document that modifies journal names in the selection list. To add code to the subscription.html document that modifies journal names in the selection list: 1.
Return to the subscription.html document in your text editor.
2.
Add the following elements to the end of the element that contains the other buttons that build the list of journals. The Change Journal button includes an onclick event handler, which calls a function named changeJournal(). You will add this function next.
3.
Add the following changeJournal() function to the end of the script section. The function is very similar to the changeItem() function you saw in the shopping list form. function changeJournal() { var selectedItem = document.forms[0].journals.selectedIndex; if (selectedItem == −1) window.alert("You must select a journal name in the list."); else { document.forms[0].journals .options[selectedItem].value = document.forms[0] .elements[31].value; document.forms[0].journals .options[selectedItem].text = document.forms[0] .elements[31].value; } }
4.
Save the subscription.html document and then open it in your Web browser. Scroll to the end of the Web page and try adding and changing some journals in the journal list. Figure 5-16 shows how the document appears.
289
CHAPTER 5
Validating Form Data with JavaScript
290
Figure 5-16
Subscription form with a selection list 5.
Close your Web browser window.
Short Quiz 3 1.
How do you create a selection list with the <select> element?
2.
How do you use the Select object to manipulate selection lists with JavaScript?
3.
How do you add options to a selection list with JavaScript?
4.
How do you remove options in a selection list with JavaScript?
5.
How do you change options in a selection with JavaScript?
Validating Submitted Data In Chapter 3, you learned about many of the event handlers that can be used in JavaScript. Two additional event handlers, onsubmit and onreset, are available for use with the
"); ...
Figure 6-3
Interface write( ) writeln( )
Conceptual example of the Document object black box
Black Box
Document
object
CHAPTER 6
Using Object-Oriented JavaScript
Another example of an object and its interface is Microsoft Word. Word itself is actually an object made up of numerous other objects. The program window (or user interface) is one object. The items you see in the interface, such as the buttons on the ribbon are used to execute methods. For example, the Bold button executes a bold method. The text of your document is the data you provide to the program. Microsoft Word is a helpful tool that you can use without knowing how the various methods work. You only need to know what each method does. To get full satisfaction out of Microsoft Word, you only need to provide the data (text) and execute the appropriate methods (such as the bold method), when necessary. In the same way, when using objects in your code, you only need to provide the necessary data (such as an employee’s gross pay) and execute the appropriate method (such as the calcNetPay() method).
316
Understanding Classes In object-oriented programming, the code, methods, attributes, and other information that make up an object are organized into classes. Essentially, a class is a template, or blueprint, that serves as the basis for new objects. When you use an object in your program, you actually create an instance of the class of the object. An instance is an object that has been created from an existing class. When you create an object from an existing class, you are said to be instantiating the object.
Class names in traditional objectoriented programming usually begin with an uppercase letter. This convention is also followed in JavaScript.
Later in this chapter, you will learn how to create, or instantiate, an object from built-in JavaScript classes and from custom classes that you write yourself. However, as a conceptual example, consider an object named BankAccount that contains methods and properties that you might use to record transactions associated with a checking or savings account. The BankAccount object is created from a BankAccount class. To use the BankAccount class, you create an instance of the class. A particular instance of an object inherits its methods and properties from a class—that is, it takes on the characteristics of the class on which it is based. The BankAccount object, for instance, would inherit all of the methods and properties of the BankAccount class. To give another example, when you create a new word-processing document, which is a type of object, it usually inherits the properties of a template on which it is based. The template is a type of class. The document inherits characteristics of the template such as font size, line spacing, and boilerplate text. In the same manner, programs that include instances of objects inherit the object’s functionality. Because objects in the browser object model are actually part of the Web browser, you do not need to instantiate them in order to use
Introduction to Object-Oriented Programming
them in your programs. For example, you do not need to instantiate a Document object from the Document class in your JavaScript programs because the Web browser automatically instantiates one for you. However, you do need to instantiate some objects from the built-in JavaScript classes that you will study next. 317
Using Built-In JavaScript Classes The JavaScript language includes the eleven built-in classes listed in Table 6-1. Each object contains various methods and properties for performing a particular type of task. Class
Description
Array
Creates new array objects
Boolean
Creates new Boolean objects
Date
Retrieves and manipulates dates and times
Error
Returns run-time error information
Function
Creates new function objects
Global
Stores global variables and contains various built-in JavaScript functions
Math
Contains methods and properties for performing mathematical calculations
Number
Contains methods and properties for manipulating numbers
Object
Represents the base class for all built-in JavaScript classes; contains several of the built-in JavaScript functions
RegExp
Contains methods and properties for finding and replacing characters in text strings
String
Contains methods and properties for manipulating text strings
Table 6-1
Built-in JavaScript classes
Instantiating an Object You can use some of the built-in JavaScript objects directly in your code, while other objects require you to instantiate a new object. The Math object is one that you can use directly in your programs without instantiating a new object. The following example shows how to use the Math object’s PI (π) property in a script: <script type="text/javascript"> // The following statement prints 3.141592653589793 document.write("The value of pi is " + Math.PI);
You will study the Date, Number, Math, and Object classes in this chapter. You will study the Array, String, and RegExp classes in Chapter 7, and the Error object in Chapter 8.
CHAPTER 6
Using Object-Oriented JavaScript
Unlike the Math object, an Array object requires you to instantiate a new object before you can use it. As you learned in Chapter 4, arrays are represented in JavaScript by the Array object, which contains a constructor named Array(). You create new arrays in your code using the new keyword and the Array() constructor. The following statement shows an example of how to instantiate an array named deptHeads:
318
var deptHeads = new Array();
The Option object is the only object in the W3C browser object model from which you can instantiate a new object. The Web browser creates all other objects in the browser object model automatically. (You studied the Option object in Chapter 5.)
You may be wondering why the preceding statement instantiates the new object using the var keyword. As you recall, the var keyword is used for declaring variables. The name you use for an instantiated object is really a variable just like an integer or string variable. In fact, programmers use the terms “variable” and “object” interchangeably. The difference is that the data the variable represents happens to be an object instead of a number or string. Recall from Chapter 1 that variables are the values a program stores in computer memory. Recall, too, that the JavaScript language also supports reference data types, which can contain multiple values or complex types of information, as opposed to the single values stored in primitive data types. In other words, in the same manner that you use a variable name to represent a primitive data type, such as an integer, in computer memory you also use a variable name to represent an object. Because the objects you declare in your JavaScript program are actually a certain type of variable, you can use the var keyword to identify them as variables. You are not required to use the var keyword when declaring any variables or objects in your programs; however, it is good practice always to do so.
Performing Garbage Collection If you have worked with other object-oriented programming languages, then you may be familiar with the term garbage collection, which refers to cleaning up, or reclaiming, memory that is reserved by a program. When you declare a variable or instantiate a new object, you are actually reserving computer memory for the variable or object. With some programming languages, you must write code that deletes a variable or object after you are through with it in order to free the memory for use by other parts of your program or by other programs running on your computer. With JavaScript, you do not need to worry about reclaiming memory that is reserved for your variables or objects; JavaScript knows when your program no longer needs a variable or object and automatically cleans up the memory for you.
Using the Date, Number, and Math Classes
Short Quiz 1 1.
Why do programmers refer to encapsulation as a black box?
2.
What is instantiation as it relates to classes, objects, and object-oriented programming?
3.
Explain how to conceptually instantiate an object from a class.
Using the Date, Number, and Math Classes In this section, you will learn how to work with three of the most commonly used JavaScript classes: Date, Number, and Math. First, you will examine the Date class.
Manipulating the Date and Time with the Date Class You can use dates in your programs to create a calendar, calculate how long it will take to do something, and so on. For instance, a Web page for a dry cleaning business may need to use the current date to calculate when a customer’s dry cleaning order will be ready. The Date class contains methods and properties for manipulating the date and time. The Date class allows you to use the current date and time (or a specific date or time element, such as the current month) in your JavaScript programs. You create a Date object with one of the constructors listed in Table 6-2. Constructor
Description
Date()
Creates a Date object that contains the current date and time from the local computer
Date(milliseconds)
Creates a Date object based on the number of milliseconds that have elapsed since midnight, January 1, 1970