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

Học JavaScript qua ví dụ part 37 pot

8 338 0

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

THÔNG TIN TÀI LIỆU

Nội dung

ptg 334 Chapter 11 • Working with Forms and Input Devices 11.3 About HTML Forms At the heart of the Web is the form. It is used to pass information from the browser to the server. Anytime you go online and order a book, trade at an auction, fill out a survey, or send an e-mail using a Web browser, you are working with a form. An HTML form offers you a number of ways to accept input, such as radio buttons, checkboxes, popup menus, hidden fields, and textboxes; these are called virtual input devices or controls. Once the form has been filled out by a user, it normally is sent to a server where the input is processed by a server-side program, such as a Java servlet, CGI, ASP.NET, or PHP application. It is important to understand how the form data is col- lected and sent to the server and then what role JavaScript has in this process. 11.3.1 Attributes of the <form>Tag All forms are in HTML documents. They begin with a <form> tag and its attributes, fol- lowed by the input fields where the user enters form information, and end with a </form> tag. <form name="form1" id="form1" action="URL to server program" method="post"> <input type="text" name="town" id="town" /> (continue here with body of the form including input devices for filling out the form; see Table 11.4 for a complete example). </form> focus() Brings the document into focus. getElementById() Returns a reference to the first object with the specified ID. getElementsByName() Returns a collection of objects with the specified name. getElementsByTagName() Returns a collection of objects with the specified tag name. open() Begins a new document, erasing the old one. write() Writes and appends text into the current document. writeln() Same as write(), but appends a newline if in a <pre> tag. Table 11.3 Methods of the document Object (continued) Method What It Does From the Library of WoweBook.Com ptg 11.3 About HTML Forms 335 The action Attribute. The action attribute is assigned the URL of the server program that will process the form data. After the user enters the information requested in the form, he or she will normally click a Submit button. That button might say “Order now,” “Send Your Order!” or simply “Submit.” When this button is clicked, the browser goes to the value in the action attribute to see where to send the data, which is normally the URL of a PHP, Perl CGI, or ASP script. The URL can be a relative or absolute URL (e.g., http://localhost/cgi-bin/validate.pl or simply cgi-bin/validate.pl or validate.php, etc.). When the form data is sent to the server program, it is processed further, validated, sent to a database or file, used in an e-mail, and so on. Form data doesn’t always get sent to a server program. It might be used by JavaScript to pass information to functions, cookies, and so on. To prevent the form from directing the page to a server, the action attribute can be assigned the empty string or simply be omitted, in which case the form data will not be sent. The method Attribute. A method attribute can be assigned to the <form> tag. The method attribute indicates how the form data will be sent to the server. Simply put, for pure queries, the GET method is normally used, and for submitting form data, the POST method is used. (The method names are not case sensitive.) The GET method is the default (does not need to be specified) and is used every time the browser requests a document. The GET method is preferable for operations that will not affect the state of the server; that is, simple document retrieval, queries, database lookups, bookmarking, and the like. It is the only method used for retrieving static HTML files and images. The GET method passes data to the server by appending the data to the URL (called the query string). The query string, prepended with a question mark, is a URL-encoded string consisting of name/value pairs. It can be seen in the Loca- tion bar of the browser as soon as the user clicks the Submit button in a form. In Figure 11.5 the name/value pairs being sent to the server are color=yellow. You can also view HTTP headers of a page while browsing with a Firefox add-on called Live Headers (http://livehttpheaders.mozdev.org/). See Figures 11.5 and 11.6. The POST method is preferred for handling operations that might change the state of the server, such as adding or deleting records from a database, uploading files, sending e-mail, and so on. The POST method is the most commonly used alternative when send- ing form data (see Figure 11.6). The post data is URL encoded in the same way it is with the get method, but it is posted to the server as a message body, similar to an e-mail mes- sage, rather than in a URL. The post method can be used when sending large amounts of data and is not shown in the Location bar of the browser, although it can be viewed as View Source under the browser’s View option. If you try to backbutton post data, the browser normally sends you a warning so that you do not destroy or lose a previous transaction. This caution presumes that because the post method was used, there might be some permanent change to the state of the server. From the Library of WoweBook.Com ptg 336 Chapter 11 • Working with Forms and Input Devices Figure 11.5 Firefox Live Headers shows how the GET method sends data in a query string appended to a URL and a question mark. Figure 11.6 Firefox Live Headers shows Post data sent as part of the HTTP header. From the Library of WoweBook.Com ptg 11.3 About HTML Forms 337 A summary of the steps in producing a form follows: 1. START: Start the form with the HTML <form> tag. 2. ACTION: The action attribute of the <form> tag is the URL of the server-side (CGI) script that will process the data input from the form. 3. METHOD: Provide a method on how to process the data input. The default is the get method. 4. CREATE: Create the form with buttons, boxes, and whatever looks attractive using HTML tags and fields. 5. SUBMIT: Create a submit button so that the form can be processed. This will launch the PHP, ASP.NET, or CGI script listed in the action attribute. 6. END: End the form with the </form> tag. Table 11.4 shows the various form input types. Table 11.4 HTML Form Controls Input Type Attribute Description button name, id Creates a generic button for user input. It has no default action. text name, id, size, maxlength Creates a textbox for user input. size specifies the size of the textbox. maxlength specifies the maximum number of characters allowed. textarea name, id, size, rows, cols Creates a text area that can take input spanning multiple lines. rows and cols specify the size of the box. password name, id, value Like textbox but input is hidden. Asterisks appear in the box to replace characters typed. checkbox name, id, value Displays a square box that can be checked. Creates name/value pairs from user input. Multiple boxes can be checked. radio name, id, value Like checkboxes, except only one button (or circle) can be checked. select name, id, option, size, multiple Provides popup menus and scrollable lists. Only one can be selected. Attribute multiple creates a visibly scrollable list. A size of 1 creates a popup menu with only one visible box. file name, id Specifies files to be uploaded to the server. MIME type must be multipart/form-data. hidden name, id, value Provides name/value pair without displaying an object on the screen. Continues From the Library of WoweBook.Com ptg 338 Chapter 11 • Working with Forms and Input Devices First let’s see how input gets into the form by looking at a simple document (see Figure 11.7) and the HTML code used to produce it (see Example 11.3). The user will be able to click a button or enter data in the textbox. The input in this example won’t be processed when the Submit button is clicked. Nothing will be displayed by the browser. submit name, id, value When clicked, executes the form; launches cgi. image src, name, id, value, align Same as submit button, but displays an image instead of text. The image is in a file found at src. reset name, id value Resets the form to its original position; clears all input fields. Figure 11.7 The life cycle of a fillout form. EXAMPLE 11.3 <html> <head><title>An HTML Form</title></head> <body> <big> 1 <form name="form1" id="form1" action="http://localhost/formtest.php" method="GET"> <p><fieldset><legend> All About You</legend></p> Type your name here: 2 <input type="text" name="your_name" size="50" /> <p> Talk about yourself here:<br /> 3 <textarea name="comments" id="comments" align="left" rows="5" cols="50">I was born </textarea> </p> Table 11.4 HTML Form Controls (continued) Input Type Attribute Description Server PHP ASP Perl Browser/Fillout Form Form data processed here Form data processed here CGIHTTP http://webserver/from.html name address credit card San Francisco London New York Tokyo Submit From the Library of WoweBook.Com ptg 11.3 About HTML Forms 339 <p>Choose your food: <strong> 4 <input type="radio" name="choice" id="choice1" value="burger"/>Hamburger <input type="radio" name="choice" id="choice2" value="fish"/>Fish <input type="radio" name="choice" id="choice3" value="steak"/>Steak <input type="radio" name="choice" id="choice4" value="yogurt"/>Yogurt </p> <p>Choose a work place:<br /> 5 <input type="checkbox" name="place" id="place1" value="LA"/>Los Angeles<br /> <input type="checkbox" name="place" id="place2" value="SJ"/>San Jose<br /> <input type="checkbox" name="place" id="place3" value="SF" checked />San Francisco </p> <p><b>Choose a vacation spot:</b><br /> 6 <select multiple name="location" id="location"> <option selected value="hawaii"> Hawaii </option> <option value="bali">Bali </option> <option value="maine">Maine </option> <option value="paris">Paris </option> </select> </p> <p></fieldset></p> 7 <input type="submit" value="Submit"/> 8 <input type="reset" value="Clear"/> </strong> 9 </form> </big> </body> </html> EXPLANATION 1 This is the beginning of a <form> tag that specifies where the browser will send the input data and the method that will be used to process it. The default method is the GET method. When the data is submitted, a server-side program, in this ex- ample a PHP script, will be executed by the server on the local machine. (CGI scripts were the traditional way to process data submitted on a server.) Continues EXAMPLE 11.3 (CONTINUED) From the Library of WoweBook.Com ptg 340 Chapter 11 • Working with Forms and Input Devices 2 The input type is a textbox that will hold up to 50 characters. When the user types text into the textbox, that text will be stored in the user-defined name value, your_name. For example, if the user types Stefan Lundstrom, the browser will as- sign to the query string, your_name=Stefan Lundstrom. If assigned a value attribute, the text field can display a default text string that appears in the textbox when it is first displayed by the browser. The id attribute can be used by JavaScript to ma- nipulate the form element. 3 The user is asked for input. The text area is similar to the text field, but will allow input that scans multiple lines. The <textarea> tag will produce a rectangle named “comments” with dimensions in rows and columns (5 rows × 50 columns) and an optional default value (I was born ). 4 The user is asked to pick from a series of menu items. The first input type is a list of radio buttons. Only one button can be selected at a time. The input type has two attributes: a type and a name. The value of the name attribute “choice”, for example, will be assigned “burger” if the user clicks on the Hamburger option. choice=burger is passed onto the PHP program. And if the user selects Fish, choice=fish will be as- signed to the query string. These name/value pairs are used to build a query string to pass onto the PHP program after the Submit button is clicked. 5 The input type this time is in the form of checkboxes. More than one checkbox can be selected. The optional default box is already checked. When the user se- lects one of the checkboxes, the value of the name attribute will be assigned one of the values from the value attribute; place=LA if Los Angeles is checked. 6 The user is asked for input. The <select> tag is used to produce a popup menu (also called a drop-down list) or a scrollable list. The name option is required. It is used to define the name for the set of options. For a popup menu, the size attribute is not necessary; it defaults to 1. The popup menu initially displays one option and expands to a menu when that option is clicked. Only one selection can be made from the menu. If a size attribute is given, that many items will be displayed. If the multiple attribute is given (as <select multiple name=“whatev- er”>), the menu appears as a scrollable list, displaying all of the options and the user can select more than one option by holding down the Ctrl key while click- ing the option. 7 If the user clicks the Submit button, the PHP script listed in the form’s action at- tribute will be launched. The form data will be URL encoded and sent to the serv- er program assigned to the form’s action attribute. 8 If the reset button (“Clear”) is pressed, all input boxes are reset to their defaults. 9 This tag ends the form. The output is shown in Figure 11.8. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 11.4 JavaScript and the form Object 341 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. From the Library of WoweBook.Com . Library of WoweBook.Com ptg 11.4 JavaScript and the form Object 341 11.4 JavaScript and the form Object In the previous example, the HTML form had nothing to do with JavaScript. After a form has. mark. Figure 11.6 Firefox Live Headers shows Post data sent as part of the HTTP header. From the Library of WoweBook.Com ptg 11.3 About HTML Forms 337 A summary of the steps in producing a form follows: 1 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

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

TỪ KHÓA LIÊN QUAN