Section 9.5. The input Tag


9.5. The <input> Tag

Use the <input> tag to define any one of a number of common form "controls," as they are called in the HTML and XHTML standards, including text fields, multiple-choice lists, clickable images, and submission buttons . Although there are many attributes for the <input> tag, only the name attribute is required for each element (but not for a submission or reset button; see the following explanation). And as we describe in detail later, each type of input control uses only a subset of the allowed attributes. Additional <input> attributes may be required based upon which type of form element you specify.

Table 9-1 summarizes the various form <input> types and attributes, required and optional.

Table 9-1. Required and some common form element attributes

Form tag or <input> type

Attributes (x = required; = optional; blank = not supported)

accept

accesskey

align

alt

border

cols

checked

disabled

maxlength

multiple

name

notab

onBlur

onChange

onClick

onFocus

onSelect

readonly

rows

size

src

tabindex

taborder

usemap

value

wrap

button

 

         

   

x

 

         

 

x

 

checkbox

 

       

   

x

   

   

     

 

x

 

file

         

 

x

 

 

 

 

 

hidden

                   

x

                         

x

 

image

 

   

   

   

         

x

   

password

 

         

 

x

 

 

 

x

 

radio

 

       

   

x

   

   

     

 

x

 

reset

 

         

     

   

           

 

 

submit

 

         

   

   

           

 

 

text

 

         

 

x

 

 

 

 

<button>

 

         

   

x

 

 

         

   

 

<select>

             

 

x

 

     

 

       

<textarea>

 

     

 

   

x

 

   

     


<input>

Function

Creates an input element within a form

Attributes

accept , accesskey , align , alt , border , checked , class , dir , disabled , id , lang , maxlength , name , notab , onBlur , onChange , onClick , onDblClick , onFocus , onKeyDown , onKeyPress , onKeyUp , onMouseDown , onMouseMove , onMouseOut , onMouseOver , onMouseUp , onSelect , size , src , tabindex , taborder , title , type , usemap , value

End tag

None in HTML; </input> or <input ... /> in XHTML

Contains

Nothing

Used in

form_content



You select the type of control to include in the form with the <input> tag's type attribute, and you name the field (used during the form submission process to the server; see earlier description) with the name attribute. If you do not specify it, the type field defaults to a value of text . Although the value of the name attribute is technically an arbitrary string, we recommend that you use a name without embedded spaces or punctuation. If you stick to just letters and numbers (but no leading digits) and represent spaces with the underscore ( _ ) character, you'll have fewer problems. For example, cost_in_dollars and overhead_percentage are good choices for element names ; $cost and overhead % might cause problems.

In addition, notice that the name you give to a form control is directly associated with the data that the user inputs to that control and that gets passed to the forms-processing server. It is not the same as nor does it share the same namespace with the name attribute for a hyperlink fragment or a frame document.

9.5.1. Text Fields in Forms

The HTML and XHTML standards let you include four types of text-entry controls in your forms: a conventional text-entry field, a masked field for secure data entry, a field that names a file to be transmitted as part of your form data, and a special multiline text-entry <textarea> tag. The first three types are <input> -based controls; the fourth is a separate tag that we describe later in this chapter, in section 9.7.

9.5.1.1. Conventional text fields

The most common form input control is the text-entry field for usernames, addresses, and other unique data. A text-entry field appears in the browser window as an empty box on one line and accepts a single line of user input. Eventually, that line of text becomes the value of the control when the user submits the form to the server. To create a text-entry field inside a form in your document you set the type of the <input> form element to text . Include a name attribute as well; it's required.

What constitutes a line of text differs among the various browsers. Fortunately, HTML and XHTML give us a way, with the size and maxlength attributes, to dictate the width (in the number of characters) of the text-input display box, and how many total characters to accept from the user, respectively. The value for either attribute is an integer equal to the maximum number of characters you'll allow the user to see and type in the field. If maxlength exceeds size , the text scrolls back and forth within the text-entry box. If maxlength is smaller than size , there is extra blank space in the text-entry box to make up the difference between the two attributes.

The default value for size depends on the browser, but typically it is 80 characters; the default value for maxlength is unlimited. We recommend that you set them yourself. Adjust the size attribute so that the text-entry box does not extend beyond the right margin of a typical browser window (about 60 characters with a very short prompt). Set maxlength to a reasonable number of characters; for example, two for state abbreviations, 12 for phone numbers, and so on.

A text-entry field is usually blank until the user types something into it. You may, however, specify an initial default value for the field with the value attribute. The user may modify the default, of course. If the user presses a form's Reset button, the value of the field is reset to this default value. [Reset buttons, 9.5.4.2]

All of these are valid text-entry form controls:

 <input type=text name=comments> <input type=text name=zipcode size=10 maxlength=10> <input type="text" name="address" size="30" maxlength="256" /> <input type="text" name="rate" size="3" maxlength="3" value="100" /> 

The first example is HTML and creates a text-entry field set to the browser's default width and maximum length. As we argued, this is not a good idea, because defaults may vary among browsers, and your form layout is sure to look bad with some of them. Rather, fix the width and maximum number of acceptable input characters as we do in the second example: it lets the user type in up to 10 characters inside an input box 10 characters wide. Its value is sent to the server with the name zipcode when the user submits the form.

The third example is XHTML and tells the browser to display a text-input box 30 characters wide into which the user may type up to 256 characters. The browser automatically scrolls text inside the input box to expose the extra characters.

The last text-input control is XHTML, too. It tells the browser to display a text box three characters wide, into which the user can type up to three characters. Its initial value is set to 100.

Notice that in the second and fourth examples it is implied that the user will enter certain kinds of dataa postal code or a numeric rate, respectively. Except for limiting how many , neither HTML nor XHTML provide a way for you to dictate what characters may be typed into a text-input field. For instance, in the last example field, the user may type "ABC," even though you intend the field's value to be a number less than 1,000. Your server-side application or applet must trap erroneous or mistaken input, check for incomplete forms, and send the appropriate error message to the user when things aren't right. That can be a tedious process, so we emphasize again: provide clear and precise instructions and prompts. Make sure your forms tell users what kinds of input you expect from them, thereby reducing the number of mistakes they may make when filling them out.

9.5.1.2. Masked text controls

Like the Lone Ranger and Zorro, the mask is on the good guys in a masked text field. It behaves just like a conventional text control in a form, except that the user-typed characters don't appear onscreen. Rather, the browser obscures the characters in masked text to keep such things as passwords and other sensitive codes away from prying eyes.

To create a masked text control, set the value of the type attribute to password . All other attributes and semantics of the conventional text control apply to the masked one. Hence, you must provide a name, and you may specify a size and maxlength for the field, as well as an initial value (we recommend it).

Don't be misled: a masked text control is not all that secure. The typed-in value is only obscured onscreen; the browser transmits it unencrypted when the form is submitted to the server, unless you are using a web server running Secure Sockets Layer (SSL) ( https server, for example). So, while prying eyes may not see them onscreen, devious bad guys may steal the information electronically .

9.5.1.3. File-selection controls

As its name implies, the file-selection control lets a user select a file stored on the computer and send it to the server when she submits the form. Create a file-selection control in a form by setting the value of the type attribute to file . Like other text controls, the size and maxlength of a file-selection field should be set to appropriate values, with the browser creating a field 20 characters wide, if not otherwise directed.

The browser presents the file-selection form control to the user like other text fields, accompanied by a button labeled Browse to its right. Users either type the pathname of the file directly as text into the field or, with the Browse option, select the pathname of the file from a system-specific dialog box.

The Browse button opens a platform-specific file-selection dialog box that allows users to select a value for the field. In this case, the entire pathname of the selected file is placed into the field, even if the length of that pathname exceeds the control's specified maxlength .

Use the accept attribute to constrain the types of files that the browser lets the user browse, even though it does not constrain what they may type in as the pathname. accept 's value is a comma-separated list of MIME encodings; users browse and select only files whose type matches one of those in the list. For example, to restrict the selection to images, you might add accept="image/*" to the file-selection <input> tag.

Unlike other form input controls, the file-selection field works correctly only with a specific form data encoding and transmission method. If you include one or more file-selection fields in your form, you must set the enctype attribute of the <form> tag to multipart/form-data and the <form> tag's method attribute to post . Otherwise, the file-selection field behaves like a regular text field, transmitting its value (that is, the file's pathname) to the server instead of the contents of the file itself.

All of this is easier than it may sound. For example, here is an HTML form that collects a person's name and favorite file:

 <form enctype="multipart/form-data" method=post     action="cgi-bin/save_file"> Your name: <input type=text size=20 name=the_name> <p> Your favorite file: <input type=file size=20 name=fav_file> </form> 

The data transmitted from the browser to the server for this example form has two parts . The first contains the value for the name field, and the second contains the name and contents of the specified file:

 -----------------------------6099238414674 Content-Disposition: form-data; name="the_name" One line of text field contents -----------------------------6099238414674 Content-Disposition: form-data; name="fav_file"; filename="abc" First line of file ... Last line of file -----------------------------6099238414674-- 

The browsers don't check that the user has specified a valid file. If no file is specified, the filename portion of the Content-Disposition header is empty. If the file doesn't exist, its name appears in the filename subheader, but there is no Content-Type header or subsequent lines of file content. Valid files may contain nonprintable or binary data; there is no way to restrict user-selectable file types. In light of these potential problems, the forms-processing application on the server should be robust enough to handle missing files, erroneous files, extremely large files, and files with unusual or unexpected formats.

9.5.2. Checkboxes

The checkbox form control gives users a way to select or deselect an item quickly and easily in your form. Checkboxes also may be grouped to create a set of choices, any and all of which the user may select or deselect.

Create individual checkboxes by setting the type attribute for each <input> tag to checkbox . Include the required name and value attributes. Only the values of those items selected by the user appear in the submitted form. The optional checked attribute (no value) tells the browser to display a selected (checked) checkbox and include its value when submitting the form to the server unless the user deliberately deselects (unchecks) the box.

The value of the checked checkbox submitted to the server is the text string you specify in the required value attribute. For example, in XHTML:

 <form>   What pets do you own?   <p>     <input type="checkbox" name="pets" value="dog" /> Dog   <br />     <input type="checkbox" checked="checked" name="pets" value="cat" /> Cat   <br />     <input type="checkbox" name="pets" value="bird" /> Bird   <br />     <input type="checkbox" name="pets" value="fish" /> Fish   </p> </form> 

creates a checkbox group as shown in Figure 9-3.

Figure 9-3. A checkbox group

Although part of the group, each checkbox control appears as a separate choice onscreen. Notice, too, with all due respect to dog, bird, and fish lovers, that we've preselected the Cat checkbox with the checked attribute in its tag. We've also provided text labels; the similar value attributes don't appear in the browser's window but are the values submitted with their associated name to the server if the user selects the checkbox. Also, you need to use paragraph or line-break tags to control the layout of your checkbox group, as you do for other form controls.

In the example, if the user selects Cat and Fish and submits the form, the values included in the parameter list sent to the server would be:

 pets=cat pets=fish 

9.5.3. Radio Buttons

Radio button form controls are similar in behavior to checkboxes, except that the user can select only one in the group. [*] Create a radio button by setting the type attribute of the <input> tag to radio . As with checkbox controls, radio buttons each require a name and value attribute. Radio buttons with the same name are members of a group. One of them may be checked by including the checked attribute with that element. If you don't check one in the group, the browser does it automatically for you by checking the first element in the group.

[*] Some of us are old enough, while not yet senile, to recall when automobile radios had mechanical push buttons for selecting a station. Pushing in one button popped out the previously depressed one, implementing a mechanical one-of-many choice mechanism.

You should give each radio button element a different value so that the forms-processing server can sort them out after form submission.

Here's the previous example reworked in HTML so that you get to choose only one animal as a favorite pet (see Figure 9-4):

Figure 9-4. Radio buttons allow only one selection per group

 <form>   Which type of animal is your favorite pet?   <p>     <input type=radio name=favorite value="dog"> Dog     <input type=radio checked name=favorite value="cat"> Cat     <input type=radio name=favorite value="bird"> Bird     <input type=radio name=favorite value="fish"> Fish </form> 

As in the previous example with checkboxes, we've tipped our hat toward felines, making the Cat radio button the default choice. If the user selects an alternativeBird, for instancethe browser automatically deselects Cat and selects Bird. When the user submits the form to the server, the browser includes only one value with the name "favorite" in the list of form parameters; favorite=bird , if that was the last choice.

One of the controls in a group of radio buttons always is selected, so it makes no sense to create a single radio button. Instead, use groups of two or more options, such as for On/Off and Yes/No types of form controls.

9.5.4. Action Buttons

Although the terminology is potentially confusing, there is another class of buttons for forms. Unlike the radio buttons and checkboxes described previously, these special types of form controls act immediately, their effects cannot be reversed , and they affect the entire contents of the form, not just the value of a single field. These "action" buttons (for lack of a better term ) include submit, reset, regular, and image buttons. When the user selects them, both the submit and image buttons cause the browser to submit all of the form's parameters to the forms-processing server. A regular button does not submit the form but can be used to invoke an applet to manipulate or validate the form. The reset button acts locally to erase any user input and have the form revert to its original (default) contents.

In this section, we describe the action buttons that you may create with the standard form <input> element. In the next section, we describe in detail the newer <button> tag that achieves identical effects and allows you greater control over the presentation and display of your form buttons.

9.5.4.1. Submission buttons

The submit button ( <input type=submit> ) does what its name implies, setting in motion the form's submission to the server from the browser. You may have more than one submit button in a form. You may also include name and value attributes with the submit type of form <input> button.

With the simplest submit button (one without a name or value attribute), the browser displays a small rectangle or oval with the default label "Submit." Otherwise, the browser labels the button with the text you include with the tag's value attribute. If you provide a name attribute, the browser adds the value attribute for the submit button to the parameter list and sends it along to the server. That's good, because it gives you a way to identify which submit button in a form the user selected, letting you process any one of several different forms with a single forms-processing application.

All of the following are valid submission buttons:

 <input type=submit> <input type=submit value="Order Kumquats"> <input type="submit" value="Ship Overnight" name="ship_style" /> 

The first one is in HTML and is also the simplest: the browser displays a button, labeled "Submit," which activates the forms-processing sequence when the user clicks it. It does not add an element to the parameter list that the browser passes to the forms-processing server and application.

The second example HTML button has a value attribute that makes the displayed button's label "Order Kumquats" but, like the first example, does not include the button's value in the form's parameter list.

The last example, in XHTML, sets the button label and makes it part of the form's parameter list. When the user clicks this submission button, it adds the parameter ship_style="Ship Overnight" to the form's parameter list.

9.5.4.2. Reset buttons

The reset type of form <input> button is nearly self-explanatory: it lets the user reseterase or set to some default valueall elements in the form. Unlike the other buttons, a reset button does not initiate form processing. Instead, the browser does the work of resetting the form elements. The server never knows (or cares, for that matter) whether or when the user selects a reset button.

By default, the browser displays a reset button with the label "Reset." You can change that by specifying a value attribute with your own button label.

Here are two sample reset buttons:

 <input type=reset> <input type="reset" value="Use Defaults" /> 

The first one, in HTML, creates a reset button that is by default labeled "Reset" by the browser. The second example, in XHTML, tells the browser to label the reset button with "Use Defaults." Both examples initiate the same response in the browser by resetting the form to its original contents.

9.5.4.3. Custom image buttons

The image type of form <input> element is a special submit button made out of a picture that, when selected by the user, tells the browser to submit the form to the server. Upon submission, the browser also includes the X,Y coordinates of the mouse pointer within the image in the form's parameter list, much like the mouse-sensitive image maps we discussed in Chapter 6.

Image buttons require an src attribute and, as its value, the URL of the image file. You can include a name attribute and a descriptive alt attribute for use by nongraphical browsers. Although it is deprecated in HTML 4, you also may use align to control alignment of the image within the current line of text. Use the border attribute to control the width, if any, of the frame that Netscape and Firefox put around the form image, much like the border attribute for the <img> tag. (Neither Internet Explorer nor Opera puts borders around form <input> images.)

Here are a couple of valid image buttons:

 <input type="image" src="pics/map.gif" name="map" /> <input type=image src="pics/xmap.gif" align=top name=map> 

The browser displays the designated image within the form's content flow. The second button's image is aligned with the top of the adjacent text, as specified by the align attribute. Netscape and Firefox add a border, as they do when an image is part of an anchor ( <a> ) tag, to signal that the image is a form button.

When the user clicks the image, the browser sends the horizontal offset, in pixels, of the mouse from the left edge of the image and the vertical offset from the top edge of the image to the server. These values are assigned the name of the image as specified with the name attribute, followed by .x and .y , respectively. Thus, if someone clicked the image specified in the first example, the browser would send parameters named map.x and map.y to the server.

Image buttons behave much like mouse-sensitive image maps ( usemap ), and like the programs or client-side <map> tags that process image maps, your forms processor may use the X,Y mouse-pointer parameters to choose a special course of action. You should use an image button when you need the additional form information to process the user's request. If an image map of links is all you need, use a mouse-sensitive image map. Mouse-sensitive images also have the added benefit of providing server-side support for automatic detection of shape selection within the image, letting you deal with the image as a selectable collection of shapes . Form buttons with images require you to write code that determines where the user clicked on the image and how the server can translate this position to an appropriate action.

Oddly, the HTML 4 and XHTML standards allow the use of the usemap attribute with an image button, but do not explain how such a use might conflict with normal server processing of the X,Y coordinates of the mouse position. We recommend not mixing the two, using mouse-sensitive images outside of forms and image buttons within forms.

9.5.4.4. Push buttons

Using the <input type=button> tag (or the <button> tag, described later in this chapter, in section 9.6), you create a button that the user may click, but that does not submit or reset the form. Use the value attribute to set the label on the button. The name attribute, if included in the tag, causes the supplied value to be passed to the forms-processing script.

You might wonder what value the button type provides: little or none, unless you supply one or more of the on -event attributes along with a snippet of JavaScript to be executed when the user interacts with the button. Thus empowered, these buttons provide a way for the user to initiate form content validation, update fields, manipulate the document, and perform all other kinds of client-side activity. [JavaScript Event Handlers, 12.3.3]

9.5.4.5. Multiple buttons in a single form

You can have several buttons of the same or different types in a single form. Even simple forms often have both reset and submit buttons, for example. To distinguish between them, make sure each has a different value attribute, which the browser uses for the button label. Depending on the way you program the forms-processing application, you might make the name of each button different, but it is usually easier to name all similarly acting buttons the same and let the button-handling subroutine sort them out by value. For instance (all in HTML):

 <input type=submit name=edit value="Add"> <input type=submit name=edit value="Delete"> <input type=submit name=edit value="Change"> <input type=submit name=edit value="Cancel"> 

When the user selects one of these example buttons, a form parameter named edit gets sent to the server. The value of this parameter is one of the button names. The server-side application takes the value and behaves accordingly .

Because an image button doesn't have a value attribute, the only way to distinguish among several image buttons on a single form is to ensure that they all have different names.

9.5.5. Hidden Fields

The last type of form <input> control we describe in this chapter is hidden from view. No, we're not trying to conceal anything; it's a way to embed information into your forms that the browser or user cannot ignore or alter. The browser automatically includes the <input type=hidden> tag's required name and value attributes in the submitted form's parameter list. These attributes serve to label the form and can be invaluable when sorting out different forms or form versions from a collection of submitted and saved forms.

Another use for hidden fields is to manage user-server interactions. For instance, it helps the server to know that the current form has come from a person who made a similar request a few moments ago. Normally, the server does not retain this information, and each transaction between the server and client is completely independent from all other transactions.

For example, the first form the user submits might have asked for some basic information, such as the user's name and where she lives. Based on that initial contact, the server might create a second form asking more specific questions of the user. Because it is tedious for users to reenter the same basic information from the first form, you can program the server to put the originally submitted values back into the second form in hidden fields. When the second form comes back, all the important information from both forms is there, and the second form can be matched to the first one, if necessary.

Hidden fields also may direct the server toward some specific action. For example, you might embed the following hidden field:

 <input type=hidden name=action value=change> 

Then, if you have one server-side application that handles the processing of several forms, each form might contain a different action code to help that server application sort them out.



HTML & XHTML(c) The definitive guide
Data Networks: Routing, Security, and Performance Optimization
ISBN: 596527322
EAN: 2147483647
Year: 2004
Pages: 189
Authors: Tony Kenyon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net