1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 38 pdf

10 210 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 830,93 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

As shown in Example 11.3, a document can have a number of HTML forms and input types, called controls, such as simple textboxes, radio buttons, checkboxes, and so on.. JavaScript provide

Trang 1

11.4 JavaScript and the form Object

In the previous example, the HTML form had nothing to do with JavaScript After a form

has been filled out, the user clicks a Submit button and the information is normally sent

from the browser to a server in a URL-encoded format The server then calls a server

helper application such as PHP or CGI to handle the information So where does

Java-Script come into all of this? Well, before sending the form information to the server,

JavaScript can check to see if the form was filled out properly; for example, every input

field can be validated by JavaScript It can check for empty fields or improperly filled out

fields For example, it can check for the correct format of a credit card number, e-mail

address, zip code, and so on In addition, rather than having the user submit the form,

submission can be controlled by JavaScript with its own submit() method And by

nam-ing the forms, JavaScript can handle multiple forms and input types, respond to

user-initiated events, and call functions to handle the data that was submitted

Figure 11.8 An HTML form.

Trang 2

As shown in Example 11.3, a document can have a number of HTML forms and input

types, called controls, such as simple textboxes, radio buttons, checkboxes, and so on

JavaScript provides objects that parallel HTML tags; for example, the JavaScript form

object parallels the HTML <form> tag and the JavaScript elements object parallels the

input devices such as radio buttons or checkboxes

In this section we focus on the structure of the JavaScript form object and how to use

it in terms of the Legacy DOM 0, but because DOM 1 is a standardized version, some of

the examples will include that version In this chapter you will be introduced to event

handling and forms, but events will be covered in more depth in Chapter 13 This

chap-ter also includes a section on how to validate input data, but in Chapchap-ter 17, “Regular

Expressions and Pattern Matching,” you will learn how to check all the input fields of a

form, using the magic of regular expressions and pattern matching and in Chapter 15

we will use the W3C DOM to manipulate form objects and fields (as well as other HTML

elements)

11.4.1 Naming Forms and Input Types (Controls) for Forms

The name Attribute. The HTML 4.01 specification calls the input types for forms,

controls The controls are listed in Table 11.4 The form shown in Figure 11.8 displays

the controls in the browser as textboxes, checkboxes, select menus, radio buttons, etc

The controls are created by the HTML <input type=name/value/> tag shown in Example

11.3 After the user enters data into the form or clicks a button to make a selection, the

data is collected by the browser and normally submitted to the server for further

pro-cessing The name of the form control and its value are sent as name/value pairs (e.g.,

choice=fish or city=San Francisco), to the server, where the names are used to extract the

values associated with them This means that if form data will be used in a server script

such as PHP, ASP.NET, or CGI, the name attribute is required

The id Attribute. Before the server-side program is called, JavaScript can be used to

validate the data that was entered into a form, manipulate the data, collect the form data

and display in another window, send it in an e-mail, and so on So why the id attribute?

Java-Script uses the unique id attribute and its associated document.getElementById()

method to identify all XML/HTML elements (nodes) within the document, including

form controls If the form data is not going to be sent to the server for processing, then

the name attribute is not necessary Because the form control can be referenced either by

its name or a unique ID, when creating form fields, it is customary to use both and give

them the same value when possible:1

<form>

<input type="text" id=”your_name” name=”your_name” />

<input type="text" id=”cell_phone” name=”field2” />

</form>

1 The ability to reference all of the HTML elements by unique ID was introduced by the W3C DOM,

Trang 3

Normally the id and name attribute should match but this is not always possible For

example, when creating radio buttons, one name suffices for all the buttons, because

only one of the buttons can be selected, but if you use the id attribute, each id has to be

unique as shown here:

<input type="radio" name="color" id="rbutton1" value="red" />

<input type="radio" name="color" id="rbutton2" value="green" />

<input type="radio" name="color" id="rbutton3" value="yellow" />

In Example 11.4 the radio buttons are named using the same name, but with different

IDs After the user clicks a radio button, based on his or her choice, the name/value pairs

from the form are collected by the browser and sent to the server-side program (see

Fig-ure 11.9) If the method attribute is GET, the name/value pairs will be assigned to a

query string and if the method attribute is assigned POST, the pairs will be sent in an

HTTP message body When the PHP server script called color.php is executed, it receives

the name/value pair “color=green” The PHP program can process the data, send it to a

file or database, send it in an e-mail, respond to the user, and so on The output for the

server program is shown in Figure 11.10 Notice that the id attribute values are not sent

to the server, but are retrieved via the getElementById() methods so that JavaScript can

utilize them Name attributes do not have to be unique; id attributes do.

E X A M P L E 1 1 4

<html>

<head><title>Id and Name Attributes</title></head>

<body>

<big>

1 <form name=”form1” id=”form1”

method="GET" action="http://localhost/color.php">

Pick a color: <br />

2 <input type ="radio" name="color" id="rbutton1"

value="green"/>

<label for="rbutton1">Green</label>

<br />

<input type ="radio" name="color" id="rbutton2"

value="blue"/>

<label for="rbutton2">Blue</label>

<br />

<input type ="radio" name="color" id="rbutton3"

value="yellow"/>

<label for="rbutton3">Yellow</label>

<br />

<br />

3 <input type="submit" value="Send to Server" />

4 </form>

Continues

Trang 4

5 <script type="text/javascript">

6 var rb1=document.getElementById("rbutton1");

var rb2=document.getElementById("rbutton2");

var rb3=document.getElementById("rbutton3");

7 document.write("Using the id Attribute:<br />");

document.write(rb1.value+"<br />");

document.write(rb2.value+"<br />");

document.write(rb3.value+"<br />");

</script>

</big>

</body>

</html>

E X P L A N A T I O N

1 The form is an object It has a name and an ID When this form is submitted, it

will use the GET method to send the data to the Web server You will be able to

see the input data as name/value pairs right in the location box of your browser,

the name of the input device being the key and the user input, the value

2 The input type is a radio button The name for all radio buttons is the same for all

the buttons because only one button can be selected by the user But the id

attri-bute must be unique Therefore, each radio button has the same name but a

dif-ferent ID If input data is going to be sent to a server program, the name attribute

is necessary to create the name/value pairs If the input data is going to be used by

JavaScript then the getElementById() method can use the unique value to get a

ref-erence to the input device

3 When the submit button is selected, the data input by the user is collected in

name/value pairs and sent by the browser to the server

4 The HTML form ends here

5 In the following script, JavaScript utilizes the id attribute to access the data for

each of the radio buttons

6 The getElementById() method returns a reference to the first radio button by using

its unique id The variable rb1 contains the reference.

7 Once you have a reference to the button, you can use its properties with the dot

syntax

E X A M P L E 1 1 4 (C O N T I N U E D)

Trang 5

11.4.2 The Legacy DOM with Forms

The forms[] Array. Because the document contains forms, the form object is a

prop-erty of the document object Every time you create a form in a given document, the

browser creates a unique form object and assigns it as an element of an array, called the

forms[] array The index value of the array, starting at 0, corresponds to the order in

which the form occurs in the document; the first form is assigned to forms[0], and each

successive form would get the next index value When accessing a form from JavaScript,

the first form to appear in the page would be referred to as document.forms[0] and the

next form document.forms[1], and so on See Figure 11.11.

Figure 11.9 The form from Example 11.4 using both the name and id attribute.

Figure 11.10 The PHP program responds Note the name/value pair after the ? in

the Location box.

Trang 6

If you name the form with the name attribute of the HTML <form> tag, you can use

that name to reference the JavaScript forms object Rather than saying document.forms[0]

or document.forms[1], you can reference the form by its name For example, if the first

HTML form is named myform1, the corresponding JavaScript object, document.forms[0],

can now be referenced as document.myform1 Even better, you can use the name of the

form as the index in an associative array, document.forms[“myform1”] where the name of

the form is the index value rather than a number

The elements[] Array. HTML forms contain input devices like buttons and

text-boxes, also called fields Similarly, the JavaScript form object consists of a property called

elements This is a JavaScript array that parallels all of the HTML fields within the form

Each of the input types in the elements[] array is also an object in its own right See

Figure 11.12

Figure 11.11 The JavaScript forms[] array parallels the HTML form elements.

Figure 11.12 How the elements[] array parallels the HTML input devices.

window

document

forms[0] forms[1] forms[2]

window

document

elements[0] elements[1] elements[ ] elements[0] elements[1] elements[ ]

Trang 7

When going down the DOM hierarchy, document.forms[0].elements[0] refers to the

first field in the first form The element objects also contains properties, such as the

name, type, and value of the field For example, document.forms[0].elements[0].name

ref-erences the name of the field and document.forms[0].elements[0].type refref-erences the type

of the field, such as submit, reset, button, text, radio, or checkbox.

If you name the field or input types, those names can be used to reference the

corre-sponding JavaScript object For example,

document.forms[“myform1”].elements[“your-name”].value is easier to decipher than document.forms[0].elements[0].value, although

they reference the same field value Furthermore if the forms on the page are reordered,

using the name of the form element as an associative array value makes it easier to move

the object by name rather than by resetting the index values When you start using DOM

1 and 2 in Chapter 15 the form and its elements can be assigned an id attribute The id

attribute must be unique for each element It is used with the getElementById() method

to retrieve a reference to the form or its fields, and in fact it can be used to retrieve any

other element on the page as well

The following example contains two forms, each containing input types The name

of the first form is form1 and the name of the second form is form2 Each form is an

ele-ment of the forms[] array

Properties and Methods

E X A M P L E 1 1 5

(Two Forms)

<form name="form1" id="form1">

<input type="text"

name="yourname": Type your name here /><br />

<input type="button"

name="button1" id="button1"

value="Push Button" />

</form>

<form name="form2" id="form2">

<input type="radio"

name="veggie" id="veggie1"

value="bean" />Beans

<input type="radio"

name="veggie" id="veggie2"

value="carrot"/>Carrots

</form>

Continues

Trang 8

The form object is a property and child of the document object Each form is an

ele-ment of the forms[] array and each form has properties that correspond to the HTML

attributes of the form as well as properties that describe the form As discussed

previ-ously, these properties might be objects in their own right; for example, the button

prop-erty of the form is also an object with its own properties Some of the properties of the

form object are listed in Table 11.5 and methods are listed in Table 11.6 Properties of

the elements object are listed in Table 11.7.

(Object Hierarchy using the array notations and the “name” attribute)

E X A M P L E 1 1 5 (C O N T I N U E D)

window

document

"form1" "form2"

elements[0]

"yourname" "button1" "veggie" "veggie"

"bean" "carrot"

elements[1] elements[0] elements[1]

Trang 9

Table 11.5 Properties of the forms Object

elements An array containing an element for each form field (radio button,

checkbox, button, etc.) defined within a form.

encoding MIME type (application/x-www-urlencoded or multipart/form-data).

FileUpload An object representing a file-upload form field.

where the user’s response to the submitted form will be displayed.

Table 11.6 Methods of the forms Object

reset() Resets the form fields to their default values.

Trang 10

11.4.3 Naming Forms and Buttons

How JavaScript References a Form by name or id. The <form> tag has a name

attribute that allows you to give your form a name It is somewhat easier and more

read-able to reference a form by its name than by using the array syntax, such as forms[0] and

forms[1] You will need the name attribute if you are submitting the form to a server-side

program as discussed in Section 11.4.1

Any object, including the form, can also be referenced by using its unique ID and the

getElementById() method of the document, standardized by the W3C DOM

In Example 11.6, two HTML forms are created: One contains a textbox, and the other

a button Each of the forms is given a name with the name attribute and an id In the

JavaScript program, the two forms are accessed by using the name and the id of the form

and its elements

Table 11.7 Properties of the elements Object

(read-only).

(read-only).

on (read-only).

disabled A Boolean value; if true the element is disabled so that it can’t be

modified; even if it contains a value, data from a disabled form field is not sent back to the server.

value The text that is associated with the input device, such as the text

entered into the text area or textbox, the text that appears in a button, and so on (read/write).

E X A M P L E 1 1 6

<html>

<head><title>Naming Forms object</title></head>

<body>

1 <form name="form1" id=”first_form”>

Enter your name:

2 <input type="text"

id="namefield"

name="namefield"

value="Name: " />

3 </form>

Ngày đăng: 04/07/2014, 02:20

TỪ KHÓA LIÊN QUAN