Part 4

New and Modified Form Elements

Forms have been a part of HTML since the very beginning. As Web sites have morphed into application frameworks, the basic form elements are beginning to show their age. A number of tools (including XForms and third-party add-ons like jQuery UI) have tried to give form elements a face-lift. HTML5 finally adds some much-needed attention to form elements. The standard includes several new form elements as well as a number of additions to the standard input element and new attributes that can be applied to any form element.

In this part . . .

check.pngIntroducing New Form Elements

check.pngExamining New Form Element Attributes

check.pngPlaying with New Form Input Types

New Form Elements

A number of new form elements have been introduced in HTML5. Each of these new tools adds a new capability. Of course, they’re not all supported yet, but they do show some promise. A notable subset of these form elements are designed to let a program modify a part of the page dynamically.

datalist

The datalist element allows the developer to attach a list of suggestions to a text input element. As soon as the user begins to type in the text field, the list of suggestions appears and the user can choose from the suggestions with the mouse.

      <label for = “txtList”>Your name

        <input type = “text”

               list = “names”

               id = “txtList”/>

        <datalist id = “names”>

          <option value = “Andy”>

          <option value = “Andrew”>

          <option value = “Androcles”>

        </datalist>

      </label>

The datalist element is currently supported by Opera only. You can embed an ordinary HTML <select> element (with the same id as the text element) inside the datalist object. Browsers that can support the datalist will do so, and others will display the select element.

A number of other fields (notably the number input type) have a list attribute that connects that element to a datalist. This is intended to allow a datalist to be connected to other kinds of input, but there is little support yet for this behavior.

fieldset

The fieldset element isn’t technically new to HTML5, but it’s not widely used by developers. All form elements are supposed to be embedded in some sort of block-level element, and the fieldset is the obvious tool for the job. By default, the fieldset draws a simple black border around its child tags. Use the <legend> tag to add a label to the fieldset.

  <form action = “”>

    <fieldset>

      <legend>My Form</legend>

      <label for = “myInput”>

        <input type = “text”

               id = “myInput” />

      </label>

    </fieldset>

  </form>

The fieldset element is supported in all major browsers.

keygen

The keygen element generates an encryption key for passing encrypted data to a server.

      <label for = “key”>keygen

        <keygen id = “key”

                keytype = “rsa”

                challenge = “openSesame” />

      </label>

The <keygen> tag has a number of parameters:

check.png keytype: Specifies the type of encryption. (rsa is standard.)

check.png challenge: A string that is passed along with the public key. (This is normally specified by the server.)

The keygen element is hotly debated in the HTML5 community. Some security experts consider its encryption mechanism already obsolete, and use of the tool requires knowledge of encryption that a relatively small number of Web developers possess. The keygen element isn’t currently supported in any browser, and it may not become a part of the standard.

label

Like the fieldset element, the label has been around for some time but has been underutilized. The label tag allows you to attach an HTML element to a form input element. The for attribute holds the id of the element related to the label. Form elements are often embedded into labels to simplify CSS formatting, and the label can offer some user-interface advantages. For example, if a label is attached to a check box or radio option, the user can click the label or the option to make a choice.

tip.eps Some Web developers embed an input tag inside the corresponding label for easier CSS formatting. I use that technique throughout this reference.

Use of fieldsets, labels, and some basic CSS eliminates the need to use tables for form layout. The following CSS shows one easy way to make a form line up nicely without adding the extra complexity of tables for layout management:

  <style type = “text/css”>

    label{

      display: block;

      width: 60%;

      text-align: right;

      margin-right: 1em;

    }

    input {

      width:40%;

    }

</style>

meter

The meter tag indicates a numeric value that falls within a range.

   <p>

    A

    <meter min = “0”

           max = “10”

           value = ”7”></meter>

  </p>

The meter tag can be placed in a form or anywhere else it is desirable to indicate that a value falls within a prescribed range. The meter tag supports a number of attributes:

check.png value: If this is not specified as an attribute, the first numeric value inside the <meter></meter> pair will be seen as the value.

check.png max: The maximum possible value of the item.

check.png min: The minimum possible value of the item.

check.png high: If the value can be defined as a range, this is the high end of the range.

check.png low: If the value can defined as a range, this is the low end of that range.

check.png optimum: This is the optimal value of the element.

The value, high, low, and optimum values should all be between min and max. No particular display mechanism is indicated for this element, though the webkit-based browsers currently display a small bar graph. Note that the meter element is used to output a numeric element. Use <input type = “range”> for numeric input within a range.

The meter tag is often used in a form, but it can occur anywhere in a document. The value of the meter can be changed dynamically through JavaScript like the value of any form element.

output

The output element is meant to display text output. It indicates a section of the page that will be modified by a script (usually JavaScript). Consider the following code fragment:

  <output id = “myOutput”>

    This is the original value

  </output>

  <button onclick = “changeOutput()”>

    change the output

  </button>

When the button is pressed, it will call the changeOutput() JavaScript function, which could look like this:

  function changeOutput(){

    var myOutput = document.getElementById(“myOutput”);

    myOutput.value = “The value has changed”;

  } // end changeOutput

When this function runs, it changes the content of myOutput.

The output element is currently supported by Opera. It does not have any particular visual style associated with it.

Until usage of this element becomes more widespread, you can use the innerHTML attribute of any page element to change its content dynamically through code.

The output tag is often embedded in forms, as it’s a user-interaction element, but it can occur anywhere in the page.

progress

The <progress> tag indicates how much of a task has been completed (often marked as a percentage).

    <p>Now destroying the world. <br />

  <p>

     progress:

     <progress value = “25”

               max = “100”></progress>

  </p>

Most browsers indicate the progress as plain text, but it’s reasonable to suppose some sort of visual gauge may become available.

The progress element is expected to be modified through JavaScript code. Because it’s associated with JavaScript, progress elements are often included in forms, but they can be placed anywhere on a page.

New Form Element Attributes

In addition to the new form elements introduced in HTML5, all the form elements got a few new goodies. These new attributes and capabilities can be applied to any form element.

autofocus

The autofocus attribute can be applied to any form element. If an element has this attribute, that element will be the focus of the first user input. It’s common to apply the autofocus attribute to the first element of the form.

  <form action = “”>

    <fieldset>

      <label>name

        <input type = “text”

               autofocus />

      </label>

      <label>email

        <input type = “email”>

      </label>

    </fieldset>

  </form>

If the browser does not accept the autofocus attribute, nothing harmful will happen, and you can still use a JavaScript-based solution. Of course, it makes sense to have only one autofocus field per form.

pattern

The pattern attribute allows you to specify a regular expression used to validate the form. If the content matches the regular expression, the field will be considered valid. (See the “Validation” section later in this part for more details.) The pattern attribute should be used only when the standard validation techniques are not sufficient, as it can be difficult to debug regular expressions.

        <input type = “text”

               id = “txtPhone”

               pattern = “(d{3}) +d{3}-d{4}”

               title = “(ddd) ddd-dddd” />

When you specify a pattern, you should also include a title attribute. The title should indicate what the pattern is. The browser can use this as a tip for the user. It may also be useful to add pattern information as placeholder text. (See the next section for more information.)

See Chapter 7 of my book JavaScript & AJAX For Dummies (Wiley Publishing) for a complete description of regular expressions and how to use them for page validation.

placeholder

The placeholder attribute allows you to add a special placeholder value in your text fields. This placeholder acts as a temporary label showing the purpose of the field without requiring a label tag. As soon as the user activates the field, the placeholder text disappears.

      <input type = “text”

             placeholder = “Name” />

Not all browsers support placeholder text. Other browsers will simply ignore the placeholder attribute. Likewise, if the field is already filled in, the placeholder will not be visible. For these reasons, it’s still preferred to add a label so users know what to type in each text area. Placeholder text is especially helpful when it’s used to indicate how the input should be formatted (especially if this will be enforced by validation or a pattern).

required

The required attribute allows you to specify a particular field as required. Supporting browsers will mark all required fields (perhaps by highlighting them in red) if they aren’t filled in. Some browsers will also send a warning if the user tries to submit a form with empty required fields.

        <input type = “text”

               required />

The special :required pseudo-class allows you to apply a CSS style to all required elements in your form (giving them a border or background color, for example). Here’s an example of a CSS style for marking required elements with a red border:

  :required {

    border: 1px solid red;

  }

Validation

Form validation is one of the trickiest parts of Web development. It’s pretty easy to set up a form that asks for user information, but it can be quite difficult to be certain that the user enters information correctly. For example, an e-mail address should contain a few letters, an “at” (@) symbol, a few more letters, a period, and a top-level domain of two to four characters. Typically programmers use tricks like regular expression parsing in JavaScript to ensure the data is in the right format.

tip.eps See my book JavaScript & AJAX For Dummies (Wiley) for a complete discussion of how to do form validation with regular expressions if you need to support validation without HTML5.

HTML5 promises a much easier solution. When you use the special-purpose input elements (described in the next section), the browser will automatically check the form field to ensure it’s in a proper format. If the entry is not valid, the form will (generally) not submit, and the special :invalid CSS pseudo-class will be associated with the invalid field. Simply supply CSS to your page handling the :invalid state:

    :invalid {

      background-color: red;

    }

When this CSS state is active, any invalid fields will have the :invalid styling. For example, if you have a color field and the red background CSS style defined here, the color field will have a red background unless the user enters in a valid color (a recognized color name or hex color value). Likewise, the e-mail field will show red until a valid e-mail address is entered.

The developer doesn’t need to add any other code to the form. Simply add CSS to display invalid entries, and the browser will do the rest.

Note that if a field is required (with the required attribute), it will be considered invalid until it contains some value.

It’s possible that the browser will refuse to process a form until all fields are validated, but this behavior does not yet seem to be universal among HTML5–compliant browsers.

If you want, you can turn off the validation for any field by adding the novalidate attribute to that element.

New Form Input Types

HTML forms are centered around the humble but flexible input element. This same element is used in HTML 4 to build many different types of interface widgets, from standard text and password fields to radio buttons and check boxes. HTML5 adds a number of very useful forms of input, which help turn HTML into a more modern user-interface tool.

Although support for these tags is not universal, it’s safe to begin using them now. Any browser (even IE6) which does not understand the advanced input types will revert to input type = “text”, which will still work exactly as expected (although not with the validation and user-interface improvements of the newer tags).

tip.eps Note that the standard indicates that the various types will be supported, but the exact way the elements are supported will vary from browser to browser. For example, the e-mail field will likely look just like an ordinary text field to a user with a standard desktop machine, but the virtual keyboard on a mobile device might change to include the @ when it encounters an e-mail field.

Most of these specialty fields do support validation, so at a minimum, it’s useful to set an :invalid CSS style so the user can tell if the data is in the field

color

The color tool allows the user to choose a color using standard Web formats — recognized color names (yellow) and hex values preceded by a # symbol (#FF0033). The browser may display a color-picking tool like the ones found in word processors and image-editing programs. At the moment, most browsers simply display a text box and indicate whether the current content is a valid color name or value.

        <input type=”color”

               id = “color” />

date

Setting the input type to date indicates that you want the user to enter a date value. Some browsers (Firefox 3.5) will still display a text field, and others (Opera 10) will display a special calendar control, allowing for much more accurate and easier date selection. Still other browsers (Chrome) will include both text and a pop-up calendar. If the date is entered by text, it must be entered in a yyyy-mm-dd format.

        <input type=”date”

               id = “date” />

You can restrict the dates allowed to a specific range by applying the min and max attributes to the element.

datetime

The datetime element combines date and time into a single element. It also includes a mechanism for entering the time zone.

        <input type=”datetime”

               id = ”datetime” />

Some browsers will pop up a calendar control for the date and a formatted input for the time. Others may modify virtual keyboards for date and time input.

The official full date and time format returned from the various date and time elements is a specialized code:

yyyy-mm-ddThh:mm+ff:gg

Each of the characters in the code describes a part of the date and time:

check.png yyyy: Four digits for the year.

check.png -: An actual dash character, which must be placed between year and month. Another dash is placed between the month and the day.

check.png mm: Two digits for the month.

check.png dd: Two digits for the day.

check.png T: The capital T indicates the beginning of the time part of the code.

check.png hh: Two digits for the hour, in 24-hour format.

check.png :: The colon character between the hour and minutes. Another colon will appear between the hour and minutes of the time zone offset.

check.png mm: Two digits for the minutes.

check.png +/-/Z: The time zone offset is indicated by a capital Z (if the time is Zulu or GMT time) or the + or - symbol if time is in another time zone.

check.png ff: If the time zone is not Zulu time, indicate the number of hours offset from GMT.

check.png gg: Number of minutes offset from Zulu time. Typically this is 00, but it is possible that the time zone will be offset by 15, 30, or 45 minutes.

For example, 5:30 PM on October 11, 2010, in New York City will be indicated like this:

2010-10-11T17:30-05:00

If the user is using a browser that validates a dateTime field, the date and time will need to be in this format to be considered valid. The value of a dateTime field will be in this format, which is relatively easy for computer programs to parse and manage.

datetime-local

The datetime-local element is just like the datetime element except it does not include a time zone indicator.

        <input type=”datetime-local”

               id = “datetimeLocal” />

The datetime-local input type expects and returns a date and time in the same format as the standard datetime element, except datetime-local does not include a time zone offset.

email

The email element generally looks like a plain text field, but it validates on an e-mail address. Also, it is possible that the browser will modify the user experience in other ways. For example, mobile browsers may modify the virtual keyboard to include the @ symbol, which is always present in e-mail addresses.

        <input type=”email”

               id = “txtEmail” />

month

The month input type generates a four-digit year followed by a two-digit month. It frequently pops up the same calendar control as other date pickers, but only the year and month (yyyy-mm format) are returned.

        <input type = “month”

               id = “month” />

number

The number field allows the input of numerical data. This often consists of a text field followed by some kind of selector (for example, up and down arrows), or it might change the virtual keypad of a portable device to handle only numeric input.

        <input type = “number”

               id = “number”

               max = “10”

               min = “0” />

The number input type supports several special attributes:

check.png min: This is the minimum value allowed. If there is an onscreen input element, it will not allow a value less than the min value. The field will also not validate if the value of the field is less than the min value.

check.png max: This is the maximum allowed value. If there is an onscreen input element, it will not allow a value larger than the max value. The field will not validate if the value of the field is larger than the max value.

check.png step: This value indicates how much the visual interface tools (typically small up and down arrows) will change the value when activated.

check.png value: This is the numeric value of the element.

All attributes of the number element can be integer or floating point. However, current browsers that support this tag (Opera and Chrome) do not seem to validate as well with floating-point values as they do with integer values. For more control of numeric input, consider the range input type. (See the next section.)

range

The range input type is a long-anticipated addition to the HTML toolbox. User-interface experts have known for years that user input of integer values is very difficult to get right. Most user-interface toolkits have some sort of slider or scrollbar mechanism, which makes it easy for users to enter a numeric value visually. The <input type = “range”> construct finally adds this functionality to HTML forms.

        <input type = “range”

               id = “range”

               min = “0”

               max = “255”

               value = “128” />

The range input takes the same attributes as number, min, max, value, and step. If the browser supports the range tag, the user will see a scroller; if not, a plain-text input type will appear. When the range element becomes widespread, its use will be encouraged because it’s much easier to restrict the user’s input to a valid range (especially when the mechanism for doing so is visual and easy) than it is to check the user’s input after the fact.

However, the range type doesn’t display the exact value, and it can be harder to get precise results than with the number input type. One solution is to pair an output tag to the range, and use JavaScript to update the output when the range is changed. Here’s a sample form that incorporates this idea:

  <form action = “”>

    <fieldset>

      <input id = “myRange”

             type = “range”

             min = “0”

             max = “255”

             value = “128”

             onchange = “updateOutput()” />

      <output id = “myOutput”>128</output>

   </fieldset>

  </form>

When the range value is changed, it calls a JavaScript function called updateOutput. Here is that function:

  function updateOutput(){

    //get elements

    var myRange = document.getElementById(“myRange”);

    var myOutput = document.getElementById(“myOutput”);

    

    //copy the value over

    myOutput.value = myRange.value;

  } // end function

Like the number input type, the range can be given floating-point values if preferred.

search

The search input type is used to retrieve text that’s intended to be used as part of a search (either internally or through some searching service like Google). On most browsers, it’s displayed like an ordinary text field. It does sometimes have some special behavior. On Safari, the search field is displayed with a small x, which clears the contents of the search. On Chrome, the autocompletion features of the main search bar (which is also the URL input element in Chrome) are automatically applied to the search box.

        <input type=”search”

               id = “search” />

Like the other new input types, there’s no penalty for using the search element in browsers that don’t support it. The fallback is a plain-text input.

Note that the search element doesn’t actually do any searching. If you want to actually search for the value, you’ll still need to write some code. The search element does give you an interface consistent with the browser’s integrated search tools, but the actual behavior is still up to the programmer.

tel

The tel field is used to input a telephone number. It expects three digits followed by a dash and four digits. You may need to play with the pattern attribute if you want to allow an area code or extensions to validate.

        <input type = “tel”

               id = “tel”  />

time

The purpose of the time input type is to allow the user to enter a time. Time is stored in hh:mm format, where hh is the hour (in 24-hour format), and mm is the minutes. Some browsers will include a colon directly in the field, and some will modify the virtual keyboard with numbers and the colon character. It’s also possible that a browser will pop up some sort of custom time selector, but this isn’t yet supported in any major browsers.

        <input type = “time”

               id = “time” />

url

Use the url input type to indicate a Web address. Browsers that support this element will check for the http:// prefix. Mobile browsers may also adapt the virtual keyboard to include characters commonly found in URLs: the colon (:), forward slash (/), and tilde (~).

        <input type = “url”

               id = “url”  />

week

The week field is used to pick a week from a calendar control. It returns a value in the following format:

yyyy-Wnn

check.png yyyy: Represents a four-digit year.

check.png -: The dash character.

check.png W: The capital W character.

check.png nn: The week as a two-digit number.

Some browsers will pop up the standard calendar control. When the user selects a date (or a week), only the year and week will be returned. Other browsers will simply validate for the proper format.

        <input type = “week”

               id = “week” />

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

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