1. Trang chủ >
  2. Giáo án - Bài giảng >
  3. Tin học >

Chapter 14. Using JavaScript with Web Forms

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.5 MB, 505 trang )


276



Part III  Integrating JavaScript into Design



Figure 14-1  A basic web form.



When a user submits this form, the JavaScript code in the background checks to make sure

that the Name text box was filled in. When filled out correctly, with the name “Steve”, for example, the page displays the entered name, as shown in Figure 14-2.



Figure 14-2  When the web form is filled out correctly, the Name text box displays a greeting.



If a user fails to enter any data in the Name text box, the script displays an alert() dialog box

indicating that the field is required, as you can see in Figure 14-3.



Figure 14-3  The form displays an alert when the Name text box is empty.







Chapter 14  Using JavaScript with Web Forms



277



The code that does all this follows. You can find it in the formvalid.htm file in the companion

content. The file includes the Hypertext Markup Language (HTML) shown here:


"http://www.w3.org/TR/html4/strict.dtd">





A Basic Example









A Basic Form Example





Name (Required):















The JavaScript within the element first links to the event handler script ehandler.js,

which was developed in Chapter 11, “JavaScript Events and the Browser.” Next, it defines a

function called formValid() to process the input from the simple form, as shown in this code:

function formValid(eventObj) {

if (document.forms[0].textname.value.length == 0) {

alert("Name is required.");

if (eventObj.preventDefault) {

eventObj.preventDefault();

} else {

window.event.returnValue = false;

}

return false;



278



Part III  Integrating JavaScript into Design

} else {

alert("Hello " + document.forms[0].textname.value);

return true;

}

}



Within the formValid() function, an if conditional test uses the document.forms[] array. By

examining the first index value (0) of that array, the code finds the only form on this webpage.

The conditional tests whether the length of the textname.value property on the form is 0. If it

is, the script indicates the error using an alert() dialog box. If it is not, it displays whatever is in

the textname.value property.

The return value is important. When the submit or click event handlers are called and return

false, the browser halts the form submission process. This is why returning false is important

when validation fails. Without returning false, the default action is to continue and submit the

form. You can stop the default action in most browsers by calling the preventDefault() method. However, preventDefault() is not available in Windows Internet Explorer prior to version

9, so the script executes a conditional test to see first whether the preventDefault() method

is available. If it is, the script calls preventDefault(); otherwise, the script sets the returnValue

property of the window.event object to false to account for Internet Explorer.

The next bit of JavaScript, which appears in the HTML element, adds the submit

event to the form by using the EHandler event handler script:

var formEl = document.getElementsByTagName("form")[0];

EHandler.add(formEl,"submit", function(eventObj) { formValid(eventObj); } );



Note that to retrieve the form, the formValid() function uses the first index value of the

document.forms[] list, whereas the var formEl definition uses the getElementsByTagName

method. Both of these approaches work fine when only one form is on the page. You’ll also

frequently see script that accesses the form through its name, as shown in the next section.



Obtaining Form Data

Before you can provide feedback based on the form data, you have to get access to it. The

previous example showed how to access the form data using the document.forms[] array and

the getElementsByTagName function. This section shows a different way to perform the same

operation—using the form’s name property instead of its index.

Like other elements of an HTML page, you can set the id attribute for a form element. Here’s

the previous example with an id attribute:



Name (Required):













Chapter 14  Using JavaScript with Web Forms



279



You can then access the form using its name rather than its index, as follows:

document.forms["testform"]



Using name is useful, because in some cases, you might not know the index value of the form

you want to access, which happens sometimes when server-side or client-side code creates a

form dynamically, and you have to figure out (or worse, guess) the index value of the specific

form you need within the document. The most consistent way to ensure you can get a reference to the index value is to set the form’s id and then access it through that id. You can also

access the form directly in a nonstandard way, through the document object, but I wouldn’t

recommend it:

document.testform



This direct approach doesn’t work consistently across browsers, and it’s not that much more

effort to type it correctly anyway, like this:

document.forms["testform"]



Working with Form Information

You can access all individual elements of web forms through the DOM. The exact method for

accessing each element differs depending on the type of element. For text boxes and select

boxes (also known as drop-downs), the value property holds the text that a visitor types in or

selects. You use a somewhat different approach from value to determine the state of radio

buttons and check boxes, though, which this section explains.



Working with Select Boxes

A select box holds groups of options. Here’s an example of the HTML used to create a select

box (which you can find in the selectbox.txt file in the companion content).



Select A Constellation:







This code produces a select box like the one shown in Figure 14-4.



Figure 14-4  A select box based on the HTML example.



When a user selects an option, the select box’s value property is set to the value of the

particular option chosen. For this example, the select box named startype holds in its value

property whatever the visitor selects. You can access this property as follows:

document.forms["starform"].startype.value



For this particular example, you need to connect an event handler to the change event of the

select box, which you can do with the help of the EHander event handler script developed

in Chapter 11. The change event triggers a function each time the selection in the select box

changes, such as when the user selects an option using the drop-down menu. The page attaches the change event to the element using the EHandler script from Chapter 11.





} );



This code uses the Ehandler.add() method to add a function to the change event of the

element's ID, starselect.

In this case, the function added to the change event is a user-defined function called displayValue(), shown in Listing 14-2.

Listing 14-2  The function called when the Form’s change event is fired.

function displayValue(){

var selected = document.forms["starform"].startype.value;

alert("You selected " + selected);

}



This bit of JavaScript simply shows the value selected from the drop-down menu. For example, choosing Ursa Minor from the drop-down menu causes the alert() dialog box in Figure

14-5 to be shown.



Figure 14-5  Choosing a constellation through a form and then sending an alert() dialog box.



Note  The finished code for this example is in the sel.htm file, which is included with the Chapter

14 companion code.



The HTML for the select box includes an attribute named selected, which indicates which option is shown. The example selects an empty option so that the initial value of the select box

is blank:





282



Part III  Integrating JavaScript into Design



It’s also possible to select an option using JavaScript and the DOM. Programmatically selecting options is common on forms that have multiple inputs, where one choice automatically

causes other options to be selected.

In the following exercise, you build a web form that a pizza company might use to take orders. The company makes just a few special pizzas: one with vegetables; one with a variety

of meats; and one that is Hawaiian style, with ham and pineapple toppings. The company

would like a webpage with three buttons to help their pizza makers keep track of the pizza

types ordered. The buttons preselect the main topping on the pizza.



Selecting an option with JavaScript





1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the file pizza.htm in the

Chapter14 sample files folder (in the companion content).







2. Within the page, add the code shown here in boldface type (this is in pizza.txt in the

companion content):


"http://www.w3.org/TR/html4/strict.dtd">





Pizza





















Main Topping:















3. View the page within a web browser. You’ll see a page like this:







4. Choose one of the buttons. (Notice that the select box for Main Topping changes

accordingly.)

The heart of the example is the flip() function:

function flip(pizzatype) {

if (pizzatype.value == "Veggie Special") {

document.forms["pizzaform"].topping.value

} else if (pizzatype.value == "Meat Special")

document.forms["pizzaform"].topping.value

} else if (pizzatype.value == "Hawaiian") {

document.forms["pizzaform"].topping.value

}

}



= "veggies";

{

= "meat";

= "hampineapple";



This function examines the value of the pizzatype variable that gets passed into the function, and then, using the conditional, changes the value of the select box called topping

accordingly.

Again, the script in the portion of the page links to the EHandler event handler

script, and uses its EHandler.add method to attach click events to the buttons, in the same

way the code you’ve seen throughout this and the previous three chapters does.

var vegEl = document.getElementById("vegbutton");

var meatEl = document.getElementById("meatbutton");

var hawEl = document.getElementById("hawbutton");



283



284



Part III  Integrating JavaScript into Design

EHandler.add(vegEl,"click",function() { flip(vegEl); });

EHandler.add(meatEl,"click",function() { flip(meatEl); });

EHandler.add(hawEl,"click",function() { flip(hawEl); });



This example showed how to obtain information from a form and how to set information

within a form. Although the form doesn’t look like much, and the pizza company isn’t making

many pizzas right now, it’s growing because of the popularity of its pizzas. Future examples

in this chapter expand on this form.



Working with Check Boxes

The previous example showed select boxes, and you saw text boxes used earlier in this chapter, too. Another type of box—a check box—allows users to select multiple items. The pizzaordering scenario introduced in the previous section serves as a good example for illustrating

the check box.

Recall that in the initial pizza ordering system, when the pizza order taker selected one of

three pizza types, the “Main Topping” select box changed to reflect the main ingredient of

the pizza. However, allowing more flexibility, such as more pizza types, would be nice.

Figure 14-6 shows a new pizza prep form. The order taker can now select from a variety of

ingredients, in any combination.



Figure 14-6  Changing the order prep form to include check boxes.







Chapter 14  Using JavaScript with Web Forms



Selecting the various ingredients and clicking the Prep Pizza button displays the selected

pizza toppings on the screen, as shown in Figure 14-7.



Figure 14-7  Ordering a pizza through the new form and adding elements by using the DOM.



The code for this functionality is shown in Listing 14-3 (listing14-3.htm in the companion

content).

Listing 14-3  Using check boxes with the order form.


"http://www.w3.org/TR/html4/strict.dtd">





Pizza











Toppings:




name="toppingcheck">Sausage



name="toppingcheck">Pepperoni



name="toppingcheck">Ham



name="toppingcheck">Green Peppers



name="toppingcheck">Mushrooms



name="toppingcheck">Onions



name="toppingcheck">Pineapple














The heart of the page is the function prepza(), which starts by gathering the number of check

boxes contained within the form pizzaform. These are grouped together using the name attribute toppingcheck, as follows:

var checkboxes = document.forms["pizzaform"].toppingcheck.length;



After setting up a

element with a heading, the script uses a for loop to walk through the

check boxes. Each check box is examined to see whether its checked property is set:

if (document.forms["pizzaform"].toppingcheck[i].checked) {



Xem Thêm
Tải bản đầy đủ (.pdf) (505 trang)

×