Site icon Sir Codex

HTML5 and Even Fancier Forms

It’s a brand-new world for those of us working in the web industry. Browser vendors are ahead of the game, and are implementing HTML5 support before it becomes a W3C standard. Many web developers are already taking advantage of this by coding websites in HTML5. There’s the much ballyhooed video element, which allows you to serve streaming videos without Flash; there’s semantic document markup with elements like article and section. But what about HTML5 forms? What’s happening there?

At first glance, you may be disappointed with what HTML5 currently brings to web forms; each browser is implementing the new elements slightly differently, and the most impressive features are yet to be fully ready for prime time. However, if you dig a little deeper, there is untapped potential that you can use right away—and boy, doesn’t the future look bright for forms!

Let’s take a closer look at HTML5 forms, and uncover today’s practical applications while peering into tomorrow’s bounty. There’s something for everybody, with improved usability for mobile browsers, sweet CSS, and easier ways to drive everyday form functionality like placeholder text.

Introducing New Input Types

The current draft of the HTML5 specification brings with it 13 new input field types. Yes, thirteen brand-new, shiny ways of defining the good old input element, so make some room beside text inputs for the following:

  • email for email addresses, perfect to use immediately
  • tel for telephone numbers (some browsers may strip whitespace), fine for immediate use
  • url for web addresses, good to use now
  • color for hexadecimal color values; here’s hoping we see OS-native color pickers in the future!
  • number for whole numbers; some browsers provide up/down arrows next to the input field. You can also limit the number to a given range with the min and max attributes.
  • range for a numeric input with a slider widget; like the number input type, you can use min and max attributes to define the range. You can also use the step attribute to control the increments in which the slider moves. This is ready for use, as browsers that don’t support it will simply display a text field—but be careful how you use this one. Regardless of how cool they may look, sliders are only good for certain tasks (such as price ranges); in most cases, a regular number field will be easier for your users.
  • search for search keywords, so naturally just the tool for site searches. Be wary of the current Mac OS rendering: it looks just like the built-in Spotlight search, but there’s no overriding the styles if you need to display it differently. Take a look at the Apple website for an example of it in action.
  • date, month, week, time, datetime, and datetime-local for date-related inputs. Several exciting new fields—now we just have to wait for all the browsers to implement it.

Take a look at all the new input types in your browser.

note: What’s up doctype?

Remember: if you’re using HTML5 elements, you’ll need an HTML5 doctype. Fortunately, it’s short and sweet:

<!DOCTYPE html>

Native Autofocus and Placeholders

The people contributing to the HTML5 spec have come through with the goods for two common areas of functionality, which to date have been driven by JavaScript: autofocus and placeholder text.

Autofocus

Want to automatically focus a field in your form when the page loads? No longer do you have rely on JavaScript. You can now add a single attribute to your form field and the browser will do all the work:

<input type="text" autofocus="true" />

Okay, so not all browsers support it at the time of writing—but fear not, here’s a little jQuery to add backwards compatibility to older browsers:

inputEl = document.createElement('input');if !!('autofocus' in inputEl) {  $('input[autofocus="true"').eq(0).focus();};

This snippet creates an input field, and then checks if the autofocus attribute is supported by the field. If there’s no support, then it looks for the first field with an attribute of autofocus="true", and focuses.

note: You’re still using JavaScript, so what’s the difference?

You may wonder why you should replace one JavaScript snippet for another. Sure, we could continue to use the same old scripts to do the job, but with progressive enhancement, why not drive our industry forward, and provide a better experience for those on the cutting edge?

Placeholder Text

Have you ever had to add placeholder text to a field? Perhaps you used some JavaScript to achieve this. If so, you’ll love the new placeholder attribute. With a placeholder attribute you can take all the effort out with inline semantic HTML5 goodness.

Here’s an example for a postal code field:

<input type="text" name="postcode" id="postcode" placeholder="A1A 1A1" />

Like autofocus, browser support is still weak for this attribute. The good news is that there’s already a jQuery plugin available to add support to those browsers.

warning: Use with Caution

If you’ve read Fancy Form Design, you’ll already know that you have a lot of responsibility when using a tool as powerful as placeholders. Be wary of overusing this attribute just because you can; placeholders are good for providing example input, but shouldn’t be used as a substitute for a field’s label.

Let’s Hear It for Browser-based Validation

Imagine client-side validation for a required email address as easy as:

<input type="email" name="sample-email" id="sample-email" required="true" />

Now how about using a custom regular expression to validate an input like a postcode? That’s exactly what HTML5 promises to bring to the table.

Right now only Opera 10 includes validation support, with error text appearing below the first invalid field on submission. One catch is that the error message for a required field reads “You have to specify a value,” and the message for an invalid field reads, for example, “timATsitepoint is not a valid email address.” I’d love to see customizable error messages before discarding the trusty jQuery Validation plugin.

CSS Nouvelle Vague

Validation is cool, but it works best when presented clearly and legibly to the user. Fortunately, HTML5 allows for some neat CSS targeting.

Styling Invalid Fields

While it’s too early to use HTML5 validation, expect to see on-the-fly validation indicators driven by CSS pseudo-class selectors popping up at any moment now.

This one-liner will provide a visual clue to visitors if they make a mistake (the result is shown in Figure 1, “Using the :invalid pseudo-class to add an icon to invalid fields”):

:invalid {  background: url(images/icon-error.gif) no-repeat 95% 50%;}

Figure 1. Using the :invalid pseudo-class to add an icon to invalid fields

Indicators are all well and good, but what about when the visitor submits the form? Figure 2, “Validation messages in Opera 10.61” shows how Opera handles this (at the time of writing, Opera is the only browser with validation messages on submit).

Figure 2. Validation messages in Opera 10.61

Let’s hope they implement a way to override the styles for validation messages!

Targeting Fields with Attribute Selectors

Wouldn’t it be great if you could add some flair to all email, phone, and URL fields across your forms without having to target ids? Thanks to attribute selectors, you can! Figure 3, “A spruced-up comment form” is an example of a comment form that uses some super-simple CSS to add some design flair.

Figure 3. A spruced-up comment form

And the CSS using attribute selectors to target text, email, and url fields plus an :invalid pseudo-class selector declaration block:

/* Icons */fieldset div input[type="text"] {  background: url(images/icon-name.png) no-repeat left center;}fieldset div input[type="email"] {  background: url(images/icon-email.png) no-repeat left center;}fieldset div input[type="url"] {  background: url(images/icon-url.png) no-repeat left center;}/* Validation */:invalid {  color: red;}

Check out a live example of this comment form in action.

Rewarding Mobile Safari Users

If all these drawcards were not enough, Mobile Safari visitors using HTML5 forms (by way of iPhone, iPod touch, and iPad) are automatically rewarded with tailored keyboards for numbers (including telephone), web addresses, and email addresses. Check out the keyboards for these different fields in Figure 4, “Mobile Safari keyboards”.

Figure 4. Mobile Safari keyboards

Stuck with forms from yesteryear?

Are you struggling to get your hands on form code to upgrade your visitors’ experience to the latest and greatest? You might think that if you’re using a CMS that outputs forms automatically, you’re out of luck. Earlier in this article, we saw how a little JavaScript progressive enhancement came through with the goods and provided a way for us to use the autofocus and placeholder attributes today. Using the new field types should be no different, so here it is, some code to make it all possible. The code looks for validation rules applied with the jQuery Validation plugin, and when it finds a numerical or email validation rule, swaps out the underlying field for a new HTML5 input type:

/* * Hook into validation method to automatically upgrade fields to HTML 5 */$('input').each(function() {  // Fetch validation rules for current input element  var inputEl = this,    rules = $(inputEl).rules();  // Stop right here if there are no rules applied to this element  if (rules == undefined) {    return $(this);  }  // Run through validation rules and upgrade fields to corresponding input types    // Email  if (rules.email == true) {    inputEl.setAttribute('type','email');  }  // Number  else if (rules.digits == true) {    inputEl.setAttribute('type','number');    // If there are validation rules for min and max length set the corresponding attributes    if (rules.rangelength != undefined) {      inputEl.setAttribute('min', rules.rangelength[0]);      inputEl.setAttribute('min', rules.rangelength[1]);    } else {      if (rules.minlength != undefined) {        inputEl.setAttribute('min', rules.minlength);      }      if (rules.maxlength != undefined) {        inputEl.setAttribute('max', rules.maxlength);      }    }  }  // URL  else if (rules.url == true) {    inputEl.setAttribute('type','url');  }});

Using this code, visitors on Mobile Safari will receive with a keyboard to match each field.

note: Not Your (Input) Type?

The code above is specifically targeting email and number fields. These were selected as they’re the most useful and well-supported input types.

Other Form Elements

It doesn’t end there—the future also holds native autocomplete, progress bars, and keygen for generating public–private key pairs. Keep an eye out!

Browser Support

Take a look at browser support for HTML5 forms over at Find Me By IP. For support in the browser you’re using right now, check out The HTML5 Test.

Over to You

In the near future, you’ll no doubt see many more websites employing HTML5 forms to make coding forms easier and more robust. Visitors will benefit from sexier forms with more consistent elements and functionality. Jump on the bandwagon, and think about using some HTML5 for your next field!

Source Link: http://www.sitepoint.com/html5-forms/

Exit mobile version