Hour 22. Working with Web-Based Forms


What You’ll Learn in This Hour:

Image How HTML forms work

Image How to create the front end of an HTML form

Image How to name pieces of form data

Image How to include hidden data in forms

Image How to choose the correct form input controls for the situation

Image How to submit form data

Image How to validate form data

Image Sending form results by email


To this point, pretty much everything in this book has focused on getting information out to others. But you can also use your web pages to gather information from the people who read them.

Web forms enable you to receive feedback, orders, or other information from the users who visit your web pages. If you’ve ever used a search engine such as Google, Yahoo!, or Bing, you’re familiar with HTML forms—those single-field entry forms with one button that, when pressed, gives you all the information you are looking for and then some. Product order forms are also an extremely popular use of forms; if you’ve ordered anything from Amazon.com or purchased something from an eBay seller, you’ve used forms. In this chapter, you learn how to create your own forms, but you learn only how to create the front end of those forms. Working with the back end of forms requires knowledge of a programming language and is beyond the scope of this book.

How HTML Forms Work

An HTML form is part of a web page that includes areas where users can enter information to be sent back to you, to another email address that you specify, to a database that you manage, or to another system altogether, such as a third-party management system for your forms such as Salesforce.com.

Before you learn the HTML tags that are used to make your own forms, you should at least conceptually understand how the information from those forms makes its way back to you. The actual behind-the-scenes (the server-side or back-end) process requires knowledge of at least one programming language—or at least the ability to follow specific instructions when using someone else’s server-side script to handle the form input. At that point in the process, you should either work with someone who has the technical knowledge or learn the basics on your own. Simple form processing is not difficult, and your web hosting provider likely has several back-end scripts that you can use with minimal customization.


Note

PHP is the most popular server-side programming language; it’s supported by any web hosting provider worth its salt. You can learn more about PHP at http://www.php.net/, or you can just dive right in to learning this programming language (plus database interactivity) from the ground up in Sams Teach Yourself PHP, Apache, and MySQL All-in-One (ISBN: 0672335433). Although several other books on PHP and related technologies are available, I am partial to this one because I wrote it. It is geared toward absolute beginners with PHP or any other programming language.


Forms include a button for the user to submit the form; that button can be an image that you create yourself or a standard HTML form button that is created when a form <input> tag is created and given a type value of submit. When someone clicks a form submission button, all the information typed in the form is sent to a URL that you specify in the action attribute of the <form> tag. That URL should point to a specific script that will process your form, sending the form contents via email or performing another step in an interactive process (such as requesting results from a search engine or placing items in an online shopping cart).

When you start thinking about doing more with form content than simply emailing results to yourself, you need additional technical knowledge. For example, if you want to create an online store that accepts credit cards and processes transactions, there are some well-established practices for doing so, all geared toward ensuring the security of your customers’ data. That is not an operation that you’ll want to enter into lightly; you’ll need more knowledge than this book provides.


Note

There is a way to send form data without a server-side script, and you’ll learn about that method—which uses a mailto link in the action attribute of the <form>—later in this hour. But as you try that, be aware that it can produce inconsistent results; individual web browsers, as well as personal security settings, can cause that action to respond differently than you intended.


Before you put a form online, you should look in the user guide for your web hosting provider to see what it offers in the way of form-processing scripts. You are likely to find a readily available Perl or PHP script that you can use with only minimal configuration.

Creating a Form

Every form must begin with a <form> tag, which can be located anywhere in the body of the HTML document. The <form> tag typically has three attributes: name, method, and action:

<form name="my_form" method="post" action="myprocessingscript.php">

The most common method is post, which sends the form entry results as a document. In some situations, you need to use method="get", which submits the results as part of the URL query string instead. For example, get is sometimes used when submitting queries to search engines from a web form. Because you’re not yet an expert on forms, just use post unless your web hosting provider’s documentation tells you to do otherwise.


Note

HTML5 has undergone many improvements and additions for creating forms and form elements, but as of this writing, not all of them can be used in ways you expect. The good news is that even if you use an input type in your form that an older browser doesn’t technically support, it will still display a usable generic input field. Overall, this hour discusses only the input types you can be confident using. To stay up to date on browser support for new form-related elements and attributes, check out “Can I Use...” at http://caniuse.com/#feat=forms, which aggregates information about browser support for HTML5 and CSS3.


The action attribute specifies the address for sending the form data. You have two options here:

Image You can type the location of a form-processing program or script on a web server, and the form data will then be sent to that program. This is by far the most common scenario.

Image You can type mailto: followed by your email address, and the form data will be sent directly to you whenever someone fills out the form. However, this approach is completely dependent on the user’s computer being properly configured with an email client. People accessing your site from a public computer without an email client will be left out in the cold.

<form name="my_form" method="post" action="mailto:[email protected]">

The form created in Listing 22.1 and shown in Figure 22.1 includes just about every type of user input component you can currently use in HTML forms in modern browsers. Refer to this figure and listing as you read the following explanations of each type of input element.

Image

FIGURE 22.1 The code in Listing 22.1 uses many common HTML form elements.

LISTING 22.1 A Form with Various User-Input Components


<!DOCTYPE html>

<html lang="en">
  <head>
    <title>Guest Book</title>

    <style type="text/css">

      fieldset {
         width: 75%;
         border: 2px solid #ff0000;
      }

      legend {
         font-weight: bold;
         font-size: 125%;
      }

      label.question  {
         width: 225px;
         float: left;
         text-align: left;
         font-weight: bold;
      }

      span.question  {
         font-weight: bold;
      }

      input, textarea, select {
         border: 1px solid #000;
         padding: 3px;
      }

      #buttons {
         margin-top: 12px;
      }

    </style>
  </head>
  <body>
    <h1>My Guest Book</h1>
    <form name="gbForm" method="post" action="URL_to_script">

    <fieldset>
       <legend>Personal Information</legend>

       <p><label class="question" for="the_name">What is your
        name?</label>
       <input type="text" id="the_name" name="the_name"
              placeholder="Enter your full name."
              size="50" required autofocus /></p>

       <p><label class="question" for="the_email">What is your e-mail
              address?</label>
       <input type="email" id="the_email" name="the_email"
              placeholder="Please use a real one!"
              size="50" required /></p>
    </fieldset>

    <fieldset>
       <legend>Survey Questions</legend>

       <p><span class="question">Please check all that apply:</span><br/>
       <input type="checkbox" id="like_it" name="some_statements[]"
              value="I really like your Web site." />
       <label for="like_it">I really like your Web site.</label><br/>
       <input type="checkbox" id="the_best" name="some_statements[]"
              value="It's one of the best sites I've ever seen" />
       <label for="the_best">It's one of the  best sites I've ever
              seen.</label><br/>
       <input type="checkbox" id="jealous" name="some_statements[]"
              value="I sure wish my site looked as good as yours." />
       <label for="jealous">I sure wish my site looked as good as
              yours.</label><br/>
       <input type="checkbox" id="no_taste" name="some_statements[]"
              value="I have no taste and I'm pretty dense, so your site
              didn't do much for me." />
       <label for="no_taste">I have no taste and I'm pretty dense, so your
              site didn't do much for me.</label></p>

       <p><label for="choose_scale"><span class="question">Please rate my
              site on a scale of 1 (poor) to 10 (awesome):</span></label>
       <input type="number" id="choose_scale" name="choose_scale"
               min="0" max="10" step="1" value="5"/></p>

       <p><span class="question">Please choose the one thing you love best
              about my web site:</span><br/>
       <input type="radio" id="the_picture" name="best_thing"
              value="me" />
       <label for="the_picture">That amazing picture of you</label><br/>
       <input type="radio" id="the_cats" name="best_thing"
              value="cats" />
       <label for="the_cats">All the cat photos, of course</label><br/>
       <input type="radio" id="the_story" name="best_thing"
              value="childhood story" />
       <label for="the_story">The inspiring recap of your suburban
              childhood</label><br/>
       <input type="radio" id="the_treasures" name="best_thing"
              value="Elvis treasures" />
       <label for="the_treasures">The detailed list of all your Elvis
              memorabilia</label></p>

       <p><label for="how_improve"><span class="question">How can I
              improve my web site?</span></label><br/>
        <select id="how_improve" name="how_improve" size="4" multiple>
              <option value="You can't. It couldn't be better.">You can't.
              It couldn't be better.</option>
              <option value="More about the cats.">More about the
               cats.</option>
              <option value="More about the family.">More about the
              family.</option>
              <option value="More about Elvis.">More about Elvis.</option>
        </select></p>

    </fieldset>

    <fieldset>
       <legend>Free for All!</legend>
       <p><label for="message"><span class="question">Feel free to send
        more praise, gift offers, etc.:</span></label>
       <textarea id="message" name="message" rows="7" cols="55">
        </textarea></p>

    </fieldset>

    <div id="buttons">
      <input type="submit" value="Click Here to Submit" /> or
      <input type="reset" value="Erase and Start Over" />
    </div>

    </form>
  </body>
</html>


The code in Listing 22.1 uses a <form> tag that contains quite a few <input /> tags. Each <input /> tag corresponds to a specific user input component, such as a check box or radio button. The input, select, and text area elements contain borders in the stylesheet, so it is easy to see the outline of the elements in the form. Keep in mind that you can apply all sorts of CSS to those elements.

The next few sections dig into the <input /> tag and other form-related tags in detail.

Accepting Text Input

To ask the user for a specific piece of information within a form, use the <input /> tag. Although the tag does not explicitly need to appear between the <form> and </form> tags, it is good practice and makes your code easier to follow. You can place <input /> elements anywhere on the page in relation to text, images, and other HTML tags. For example, to ask for someone’s name, you could type the following text followed immediately by an <input /> field:

<p><label class="question" for="the_name">What is your name?</label>
<input type="text" id="the_name" name="the_name"
       placeholder="Enter your full name."
       size="50" required autofocus /></p>

The type attribute indicates what type of form element to display—a simple, one-line text entry box, in this case. (Each element type is discussed individually in this hour.) In this example, note the use of the placeholder, required, and autofocus attributes. You’ll learn about the required attribute later in this hour; the autofocus attribute automatically focuses the user’s cursor in this text field as soon as the browser renders the form. A form can have only one autofocus field. The placeholder attribute enables you to define some text that appears in the text box but disappears when you begin to type. Using this attribute, you can give the user a bit more guidance in completing your form.


Tip

If you want the user to enter text without the text being displayed on the screen, you can use <input type="password" /> instead of <input type="text" />. Asterisks (***) are then displayed in place of the text the user types. The size, maxlength, and name attributes work exactly the same for type="password" as they do for type="text". Keep in mind that this technique of hiding a password provides only visual protection; no encryption or other protection is associated with the password being transmitted.


The size attribute indicates approximately how many characters wide the text input box should be. If you are using a proportionally spaced font, the width of the input will vary depending on what the user enters. If the input is too long to fit in the box, most web browsers automatically scroll the text to the left.

The maxlength attribute determines the number of characters the user is allowed to type into the text box. If a user tries to type beyond the specified length, the extra characters won’t appear. You can specify a length that is longer, shorter, or the same as the physical size of the text box. The size and maxlength attributes are used only for those input fields meant for text values, such as type="text", type="email", type="URL", and type="tel", but not check boxes and radio buttons since those have fixed sizes.

Naming Each Piece of Form Data

No matter what type an input element is, you must give a name to the data it gathers. You can use any name you like for each input item, as long as each one on the form is different (except in the case of radio buttons and check boxes, discussed later in this chapter). When the form is processed by a back-end script, each data item is identified by name. This name becomes a variable, which is filled with a value. The value is either what the user typed in the form or the value associated with the element the user selected.

For example, if a user enters Jane Doe in the text box defined previously, a variable is sent to the form-processing script; the variable is user_name, and the value of the variable is Jane Doe. Form-processing scripts work with these types of variable names and values.


Note

Form-processing scripts are oversimplified here, for the sake of explanation within the scope of this book. The exact appearance (or name) of the variables made available to your processing script depends on the programming language of that script. But conceptually, it’s valid to say that the name of the input element becomes the name of the variable, and the value of the input element becomes that variable’s value on the back end.


To use this text field (or others) in JavaScript, remember that the text object uses the name attribute; you refer to the value of the field in the previous snippet as follows:

document.formname.user_name.value

Labeling Each Piece of Form Data

Labeling your form data is not the same as using a name or id attribute to identify the form element for later use. Instead, the <label></label> tag pair surrounds text that acts as a sort of caption for a form element. A form element <label> provides additional context for the element, which is especially important for screen reader software.

You can see two different examples in Listing 22.1. First, you can see the <label> surrounding the first question a user is asked (What is your name?). The use of the for attribute ties this label to the <input /> element with the same id (in this case, the_name):

<p><label class="question" for="the_name">What is your name?</label>
<input type="text" id="the_name" name="the_name"
       placeholder="Enter your full name."
       size="50" required autofocus /></p>

A screen reader would read to the user, “What is your name?” and then also say “text box” to alert the user it to complete the text field with the appropriate information. In another example from Listing 22.1, you see the use of <label> to surround different options in a check box list (and also a list of radio buttons, later in the listing):

<p><span class="question">Please check all that apply:</span><br/>
<input type="checkbox" id="like_it" name="some_statements[]"
       value="I really like your Web site." />
<label for="like_it">I really like your Web site.</label><br/>
<input type="checkbox" id="the_best" name="some_statements[]"
       value="It's one of the best sites I've ever seen" />
<label for="the_best">It's one of the  best sites I've ever
       seen.</label><br/>
<input type="checkbox" id="jealous" name="some_statements[]"
       value="I sure wish my site looked as good as yours." />
<label for="jealous">I sure wish my site looked as good as
       yours.</label><br/>
<input type="checkbox" id="no_taste" name="some_statements[]"
       value="I have no taste and I'm pretty dense, so your site
       didn't do much for me." />
<label for="no_taste">I have no taste and I'm pretty dense, so your
       site didn't do much for me.</label></p>

In this situation, the screen reader would read the text surrounded by the <label> tag, followed by “check box,” to alert the user to choose one of the given options. Labels should be used for all form elements and can be styled using CSS in the same manner as other container elements—the styling does not affect the screen reader, but it does help with layout aesthetics and readability.

Grouping Form Elements

In Listing 22.1, you can see the use of the <fieldset> and <legend> element three different times, to create three different groups of form fields. The <fieldset> element does just that—it surrounds groups of form elements to provide additional context for the user, whether they are accessing it directly in a web browser or with the aid of screen reader software. The <fieldset> element just defines the grouping; the <legend> element contains the text that will display or be read aloud to describe this grouping, such as the following from Listing 22.1:

<fieldset>
     <legend>Personal Information</legend>
     <p><label class="question" for="the_name">What is your name?</label>
     <input type="text" id="the_name" name="the_name"
          placeholder="Enter your full name."
          size="50" required autofocus /></p>
...
</fieldset>

In this situation, when the screen reader reads the <label> associated with a form element, as you learned in the previous section, it also appends the <legend> text, such as “Personal Information. What is your name? Text box.” The <fieldset> and <legend> elements can be styled using CSS, so the visual cue of the grouped elements can easily be made visible in a web browser (as you saw previously in Figure 22.1).

Including Hidden Data in Forms

Want to send certain data items to the server script that processes a form, but don’t want the user to see those data items? Use an <input /> tag with a type="hidden" attribute. This attribute has no effect on the display; it just adds any name and value you specify to the form results when they are submitted.

If you are using a form-processing script provided by your web hosting provider, you might be directed to use this attribute to tell a script where to email the form results. For example, including the following code emails the results to [email protected] after the form is submitted:

<input type="hidden" name="mailto" value="[email protected]" />

You sometimes see scripts using hidden input elements to carry additional data that might be useful when you receive the results of the form submission; some examples of hidden form fields include an email address and a subject for the email. If you are using a script provided by your web hosting provider, consult the documentation provided with that script for additional details about potential required hidden fields.

Exploring Form Input Controls

Various input controls are available for retrieving information from the user. You’ve already seen one text-entry option; the next few sections introduce you to most of the remaining form-input options you can use to design forms.

Check Boxes

Besides the text field, one of the simplest input type is a check box, which appears as a small square. Users can click check boxes to select or deselect one or more items in a group. For example, the check boxes listed in Listing 22.1 display after text that reads “Please check all that apply,” implying that the user could indeed check all that apply.

The HTML for the check boxes in Listing 22.1 shows that the value of the name attribute is the same for all of them:

<p><span class="question">Please check all that apply:</span><br/>
<input type="checkbox" id="like_it" name="some_statements[]"
       value="I really like your Web site." />
<label for="like_it">I really like your Web site.</label><br/>
<input type="checkbox" id="the_best" name="some_statements[]"
       value="It's one of the best sites I've ever seen" />
<label for="the_best">It's one of the  best sites I've ever
       seen.</label><br/>
<input type="checkbox" id="jealous" name="some_statements[]"
       value="I sure wish my site looked as good as yours." />
<label for="jealous">I sure wish my site looked as good as
       yours.</label><br/>
<input type="checkbox" id="no_taste" name="some_statements[]"
       value="I have no taste and I'm pretty dense, so your site
       didn't do much for me." />
<label for="no_taste">I have no taste and I'm pretty dense, so your
       site didn't do much for me.</label></p>

The use of the brackets in the name attribute ([]) indicates to the back-end processing script that a series of values will be placed into this one variable instead of using just one value (well, it might be just one value if the user selects only one check box). If a user selects the first check box, the text string I really like your Web site. is placed in the website_response[] bucket. If the user selects the third check box, the text string I sure wish my site looked as good as yours. also is put into the website_response[] bucket. The processing script then works with that variable as an array of data rather just a single entry.


Tip

If you find that the label for an input element is displayed too close to the element, just add a space between the close of the <input /> tag and the start of the label text, like this:

<input type="checkbox"
name="mini" /> <label>Mini
Piano Stool</label>


However, you might see groups of check boxes that do use individual names for the variables in the group. For example, the following is another way of writing the check box group:

<p><span class="question">Please check all that apply:</span><br/>
<input type="checkbox" id="like_it" name="liked_site" value="yes"
       value="I really like your Web site." />
<label for="like_it">I really like your Web site.</label><br/>
<input type="checkbox" id="the_best" name="best_site" value="yes"
       value="It's one of the best sites I've ever seen" />
<label for="the_best">It's one of the  best sites I've ever
       seen.</label><br/>
<input type="checkbox" id="jealous" name="my_site_sucks" value="yes"
       value="I sure wish my site looked as good as yours." />
<label for="jealous">I sure wish my site looked as good as
       yours.</label><br/>
<input type="checkbox" id="no_taste" name="am_dense" value="yes"
       value="I have no taste and I'm pretty dense, so your site
       didn't do much for me." />
<label for="no_taste">I have no taste and I'm pretty dense, so your
       site didn't do much for me.</label></p>

In this second list of check boxes, the variable name of the first check box is "liked_site" and the value (if checked) is "yes" when handled by a back-end processing script.

If you want a check box to be checked by default when the web browser renders the form, include the checked attribute. For example, the following code creates two check boxes, and the first is checked by default:

<input type="checkbox" id="like_it" name="liked_site" value="yes"
       value="I really like your Web site." checked />
<label for="like_it">I really like your Web site.</label><br/>
<input type="checkbox" id="the_best" name="best_site" value="yes"
       value="It's one of the best sites I've ever seen" />

The check box labeled I really like your site. is checked by default in this example. The user must click the check box to uncheck it and thus indicate they have another opinion of your site. The check box marked One of the best I've seen. is unchecked to begin with, so the user must click it to turn it on. Check boxes that are not selected do not appear in the form output.

Radio Buttons

Radio buttons, for which only one choice can be selected at a time, are almost as simple to implement as check boxes. The simplest use of a radio button is for yes/no questions or for voting when only one candidate can be selected.

To create a radio button, use type="radio" and give each option its own <input /> tag. Use the same name for all the radio buttons in a group, but don’t use the [] that you used with the check box, because you don’t have to accommodate multiple answers:

<input type="radio" id="vote_yes" name="vote" value="yes" checked />
<label for="vote_yes">Yes</label> <br />
<input type="radio" id="vote_no" name="vote" value="no" />
<label for="vote_no">No</label>

The value can be any name or code you choose. If you include the checked attribute, that button is selected by default. No more than one radio button with the same name can be checked.


Note

Radio buttons are named for their similarity to the buttons on old push-button radios. Those buttons used a mechanical arrangement so that when you pushed one button in, the others popped out.


When designing your form and choosing between check boxes and radio buttons, ask yourself whether the question being asked or implied that could be answered in only one way. If so, use a radio button.

Selection Lists

Both scrolling lists and pull-down pick lists are created with the <select> tag. You use this tag together with the <option> tag, as the following example shows (taken from Listing 22.1):

<p><label for="how_improve"><span class="question">How can I
     improve my web site?</span></label><br/>
<select id="how_improve" name="how_improve" size="4" multiple>
     <option value="You can't. It couldn't be better.">You can't.
          It couldn't be better.</option>
     <option value="More about the cats.">More about the cats.</option>
     <option value="More about the family.">More about the
          family.</option>
     <option value="More about Elvis.">More about Elvis.</option>
</select></p>

Unlike the text input type that you learned about briefly in a previous section, the size attribute here determines how many items show at once on the selection list. If size="2" were used in the preceding code, only the first two options would be visible and a scrollbar would appear next to the list so the user could scroll down to see the third and fourth options.


Tip

If you leave out the size attribute or specify size="1", the list creates a simple drop-down pick list. Pick lists don’t allow for multiple choices; they are logically equivalent to a group of radio buttons. The following example shows another way to choose yes or no for a question:

<select name="vote">
  <option value="yes">Yes
   </option>
  <option value="no">No
   </option>
</select>


Including the multiple attribute enables users to select more than one option at a time; the selected attribute makes an option initially selected by default. When the form is submitted, the text specified in the value attribute for each option accompanies the selected option.

No HTML tags other than <option> and </option> should appear between the <select> and </select> tags, with the exception of the <optgroup> tag (not shown in Listing 22.1). The use of <optgroup>, as in the following snippet, enables you to create groups of options (that’s where the name optgroup comes from) with a label that shows up in the list but can’t be selected as an “answer” to the form field. For example, this snippet:

<select name="grades">
     <optgroup label="Good Grades">
          <option value="A">A</option>
          <option value="B">B</option>
     </optgroup>
     <optgroup label="Average Grades">
          <option value="C">C</option>
     </optgroup>
     <optgroup label="Bad Grades">
          <option value="D">D</option>
          <option value="F">F</option>
     </optgroup>
</select>

produces a drop-down list that looks like this:

Good Grades
   A
   B
Average Grades
   C
Bad Grades
   D
   F

In this situation, only A, B, C, D, and F are selectable, but the <optgroup> labels are visible.

Text Fields, Text Areas, and Other Input Types

The <input type="text"> attribute mentioned earlier this chapter allows the user to enter only a single line of text. When you want to allow multiple lines of text in a single input item, use the <textarea> and </textarea> tags to create a text area instead of just a text field. Any text you include between these two tags is displayed as the default entry in that box. Here’s the example from Listing 22.1:

<textarea id="message"  name="message" rows="7" cols="55">Your
      message here.</textarea>

As you probably guessed, the rows and cols attributes control the number of rows and columns of text that fit in the input box. The cols attribute is a little less exact than rows and approximates the number of characters that fit in a row of text. Text area boxes do have a scrollbar, however, so the user can enter more text than what fits in the display area.

Let’s turn back to the basic <input /> element for a minute, however, because HTML5 provides many more type options for input than simply “text,” such as built-in date pickers. The downside is that not all browsers fully support many of those options (such as the built-in date picker). Here are a few of the different input types (some new, some not) that are fully supported but that we haven’t discussed in any detail in this lesson:

Image type="email"—Appears as a regular text field, but when form validation is used, the built-in validator checks that it is a well-formed email address. Some mobile devices display relevant keys (the @ sign, for example) by default instead of requiring additional user interactions.

Image type="file"—Opens a dialog box to enable you to search for a file on your computer to upload.

Image type="number"—Instead of creating a <select> list with <option> tags for each number, this type enables you to specify a min and max value, and the step-between numbers, to automatically generate a list on the browser side. You can see this in use in Listing 22.1.

Image type="range"—Much like the number type just covered, this type enables you to specify a min and max value and the step-between numbers, but in this case, it appears as a horizontal slider.

Image type="search"—Appears as a regular text field, but with additional controls sometimes used to allow the user to clear the search box using an x or similar character.

Image type="url"—Appears as a regular text field, but when form validation is used, the built-in validator checks that it is a well-formed URL. Some mobile devices display relevant keys (the .com virtual key, for instance) by default instead of requiring additional user interactions.

You can stay up to date with the status of these and other <input> types using the chart at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input.

Using HTML5 Form Validation

Many features in HTML5 have made web developers very happy people. One of the simplest yet most life-changing might be the inclusion of form validation. Before HTML5 form validation existed, we had to create convoluted JavaScript-based form validation, which caused headaches for everyone involved.

But no more! HTML5 validates forms by default, unless you use the novalidate attribute in the <form> element. Of course, if you do not use the required attribute in any form fields themselves, there’s nothing to validate. As you learned in a previous section, not only are fields validated for content (any content at all)—they are validated according to the type that they are. For example, in Listing 22.1, we have a required field for an email address:

<p><label class="question" for="the_email">What is your e-mail
     address?</label>
<input type="email" id="the_email" name="the_email"
     placeholder="Please use a real one!"
     size="50" required /></p>

In Figures 22.2 and 22.3, you can see that the form automatically validates for the presence of content, but then also slaps you on the wrists when you try to enter a junk string in the field instead of an email address.

Image

FIGURE 22.2 Attempting to submit a form with no content in a required field causes a validation error.

Image

FIGURE 22.3 Attempting to submit a form with badly formed content in a field expecting an email address causes a validation error.

You can use the pattern attribute of the <input /> field to specify your own pattern-matching requirements. The pattern attribute uses regular expressions, which is a large enough topic to warrant its own book. But consider a little example. If you want to ensure that your <input /> element contains only numbers and letters (no special characters), you could use the following:

<input type="text" id="the_text" name="the_text"
     placeholder="Please enter only letters and numbers!"
     size="50" pattern="[a-z,A-Z,0-9]" required />


Note

Validation of email addresses begins and ends with it simply looking like an email address. This sort of pattern matching is really the only type of “validation” that you can do with email addresses, short of a time-consuming back-end processing script.


The pattern here says that if the field contains any letter between a and z, letter between A and Z (case matters), and number 0 and 9, it’s valid. To learn more about regular expressions without buying an entire book, take a look at the online tutorial at http://regexone.com/.

Submitting Form Data

Forms typically include a button that submits the form data to a script on the server or invokes a JavaScript action. You can put any label you like on the Submit button with the value attribute:

<input type="submit" value="Place My Order Now!" />

Unless you change the style using CSS, a gray button is sized to fit the label you put in the value attribute. When the user clicks it, all data items on the form are sent to the email address or script specified in the form’s action attribute.

You can also include a Reset button that clears all entries on the form so that users can start over if they change their minds or make mistakes. Use the following:

<input type="reset" value="Clear This Form and Start Over" />

If the standard Submit and Reset buttons look a little bland to you, remember that you can style them using CSS. If that’s not good enough, you’ll be glad to know that there’s an easy way to substitute your own graphics for these buttons. To use an image of your choice for a Submit button, use the following:

<input type="image" src="button.gif" alt="Order Now!" />

The button.gif image displays on the page, and the form also is submitted when a user clicks the button.gif image. You can include any attributes normally used with the <img /> tag, such as alt and style.

The form element also includes a generic button type. When using type="button" in the <input /> tag, you get a button that performs no action on its own but can have an action assigned to it using a JavaScript event handler (such as onclick). However, because you need JavaScript interaction for that, it’s best to stick with the submit, rest, or image types, or use the actual <button> element (in IE 9 and greater), which has type attributes of submit and rest and allows for slightly more flexibility in styling than the <input> elements of the same type.

Summary

This hour demonstrated how to create HTML forms, which allow your visitors to provide information to you when they are hooked up to a back-end processing script (which is outside the scope of this book).

You learned about all the major form elements, including a little about how form-processing scripts interpret the names and value attributes of those elements. When you are ready to try a back-end form-processing script, you’ll be well versed in the front-end details.

We stopped short of doing anything in-depth with that information because form handling requires an external script to process that form. However, there is plenty to do to set up a form that looks and acts just the way you want it to, including form validation, so you have a lot to practice before taking that next step into form interactivity.

Table 22.1 summarizes the HTML tags and attributes covered in this chapter.

Image
Image
Image

TABLE 22.1 HTML Tags and Attributes Covered in Chapter 22

Q&A

Q. Is there any way to create a large number of text fields without dealing with different names for all of them?

A. Yes. If you use the same name for several elements in the form, their objects form an array. For example, if you defined 20 text fields with the name member, you could refer to them as member[0] through member[19]. This also works with other types of form elements.

Q. If HTML5 contains form validation, do I ever have to worry about validation again?

A. Yes, you do. Although HTML5 form validation is awesome, you should still validate the form information that is sent to you on the back end. Back-end processing is outside the scope of the book, but as a rule, you should never trust any user input—always check it before performing an action that uses it (especially when interacting with a database).

Workshop

The Workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

1. What HTML code do you use to create a guestbook form that asks someone for his or her name and gender? Assume that you have a form-processing script set up at /scripts/formscript and that you need to include the following hidden input element to tell the script where to send the form results:

<input type="hidden" name="mailto" value="[email protected]" />

2. If you created an image named submit.gif, how would you use it as the Submit button for the form you created in Question 1?

3. Which of these attributes of a <form> tag determines where the data will be sent?

a. action

b. method

c. name

Answers

1. You use HTML code similar to the following (with the appropriate DOCTYPE and other structural markup, of course):

<form name="form1" method="post" action="/scripts/formscript">
<input type="hidden" name="mailto" value="[email protected]" />
<p><label for="name">Your Name:</label>
<input type="text" id="name" name="name" size="50" /></p>
<p>Your Gender:
<input type="radio" id="male" name="gender"
     value="male" /> <label for="male">male</label>
<input type="radio" id="female" name="gender"
     value="female" /> <label for="female">female</label>
<input type="radio" id="go_away" name="gender"
     value="mind your business" />
    <label for="go_away">mind your business</label></p>
<p><input type="submit" value="Submit Form" /></p>
</form>

2. Replace the following code:

<input type="submit" value="Submit Form" />

with this code:

<input type="image" src="submit.gif" />

3. a. The action attribute determines where the data is sent.

Exercises

Image Create a form using all the different types of input elements and selection lists to make sure you understand how each of them works.

Image Learn a little bit about regular expressions, and implement some custom validation using the pattern attribute.

Image Investigate the form-handling options at your web hosting provider, and use a script that the web hosting provider made available to you to process the form you created in the previous exercise.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.236.255