forms – HTML5 Doctor http://html5doctor.com helping you implement HTML5 today Tue, 21 Jun 2016 09:50:49 +0000 en-US hourly 1 The woes of date input https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/ https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/#comments Tue, 19 Jan 2016 14:39:31 +0000 http://html5doctor.com/?p=5961

Related Posts:

]]>
One of the many new input types that HTML5 introduced is the date input type which, in theory, should allow a developer to provide the user with a simple, usable, recognisable method of entering a date on a web page. But sadly, this input type has yet to reach its full potential.

Briefly, the date input type is a form element that allows the capture of a date from a user, usually via a datepicker. The implementation of this datepicker is up to the browser vendor, as the HTML5 specification does not tell vendors how to implement the input’s UI.

The input itself can of course be used without using any of its available attributes:

<label for="when">Date:</label>
<input id="when" name="when" type="date">

Or you can specify minimum and maximum date values via the min and max attributes, ensuring that a user can only choose dates within a specific range:

<label for="when">Date:</label>
<input id="when" name="when" type="date" min="2016-01-01" max="2016-12-01">

You can also use the step attribute to specify, in days, how a date can increment. The default is 1.

This of course is the theory and a fine reality it would be, if it were so but alas it is not.

Features

Rather than talk about browser support for the date input type, I will instead talk about the various features that are part of this input type:

The input field

Neither Firefox nor Safari support this input type; it is treated as a simple text field with no formatting and no special interaction.

Microsoft Edge has no special interactions and in fact the input field appears to be read-only.

Chrome and Opera have the same implementations which display a date placeholder (or date value if the input’s value attribute has been set) using the user’s system settings’ date format. There are also some controls that allow the user to clear the input field, some arrows to cycle up and down between values, and an arrow that will open a datepicker (see Figure 1). There are some WebKit prefixed pseudo selectors available that allow you to change the appearance of the various bits within the input date field.

Screenshot of WebKit's native date input on Chrome

Figure 1. – WebKit’s date input field as seen on Chrome

The min and max attributes

All of those browsers that support the date input type also support the min and max attributes.

Chrome and Opera both work fine if both the min and max attributes are set, but the UI is poor when only one of them is set. In these browsers, the date input displays up and down arrows for the user to change each value (day, month, and year). If a date input has a minimum value set at today’s date, then if the user highlights the year and then clicks the down arrow, the year will change to 275760 as the arrows cycle between the valid values and, since no maximum has been set, the default maximum is used (see Figure 2). This has been reported as a bug but has been marked as “won’t fix” as apparently it is the desired behaviour, I disagree.

Screenshot of WebKit's native date input on Chrome showing the year cycling to 275760

Figure 2. – WebKit’s buggy date input field with a min value set but no max

Something similar happens when only a max value is set in that pressing the up arrow will cycle around to the year 0001, which is the default minimum. Again this leads to a very confusing UX for the user, so please use both min and max where possible.

With Android, the setting of these attributes can cause some weird quirks with the datepicker.

The step attribute

None of the browsers tested support the step attribute.

The datepicker

Firefox and Safari do not support the date input type and therefore do not open a datepicker on desktop. But they do open a device’s native datepicker on mobile devices when the date input field receives focus.

Microsoft Edge opens a datepicker, but its UI is very poor (see Figure 3).

Screenshot of the the Edge's datepicker, which displays a list of selectable dates with one highlighted and two buttons at the bottom, once with a tick and the other with an X

Figure 3. – Microsoft Edge’s native datepicker

Chrome and Opera open a fairly decent datepicker on desktop but you cannot style it at all. It looks how it looks (see Figure 4), and there’s nothing that you can do about it, no matter what your designer says. With these browsers you can disable the native datepicker if you want and implement your own, but this will not work with mobile devices. This gives you the best of both worlds: you can implement a nicer datepicker for desktop and let a device use its own native datepicker.

Screenshot of WebKit's native datepicker and date input on Chrome

Figure 4. – WebKit’s native datepicker and date input field as seen on Chrome

All the native datepickers that I tested on Android displayed some sort of confusing display quirks when valid min and max attribute are set. A user is correctly restricted from selecting a date outside of the specified range, but the visual datepickers often display “previous”, “current”, and “next” values for day, month, and year, and the values displayed for “previous” are either empty (in the case of the month) or set to 9999 (in the case of the year, see Figure 5).

Screenshot of the native datepicker on Android 4.3, with a selected date and the previous year set to 9999

Figure 5. – The native datepicker on Android 4.3

Events

Like most of the other input fields, the date input supports the input and changed events. The input event is fired every time a user interacts with the input field, while the change event is usually only fired when the value is committed, i.e. the input field loses focus.

For those browsers mentioned above that support the native date input field, no specific events are fired that will allow you to determine if the user has done anything “date specific” such as opened or closed the datepicker, or cleared the input field. You can work out if the field has been cleared by listening for the input or change events and then checking the input field’s value.

If you have an event listener set up for the change event and one for the input event, changed will never actually fire as input takes precendence.

Conclusion

So, what can we deduce from all this? Should we use the input date type or not? And as usual the answer is “it depends” as only you know what you’re building and how and where it will be used, so it might fit perfectly for your needs or it might not.

I think in general it’s safe to use the input date type on occasions where a min and max does not need to be set as the quirks when these attributes are used are too irritating to ignore. Since not all browsers support a datepicker and you will have to get one from somewhere else to support these browsers, I would also recommend turning off the datepicker for all desktop browsers (using the method linked to above) as this will still allow devices to use their own.

Have fun!

The woes of date input originally appeared on HTML5 Doctor on January 19, 2016.

]]>
https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/feed/ 11
HTML5 forms input types https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/ https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/#comments Thu, 28 Feb 2013 14:00:01 +0000 http://html5doctor.com/?p=4993 In the first article in this series we looked at the history of HTML5 forms and many of the new attributes available to us. In this second and final part of the series, we'll look at the new input types available in HTML5. As we'll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now.

]]>
In the first article in this series we looked at the history of HTML5 forms and many of the new attributes available to us. In this second and final part of the series, we’ll look at the new input types available in HTML5. As we’ll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Note: As this article is a book excerpt, browser renderings of attributes and input types may have altered since the screenshots were taken. Additionally, browser support may have increased since publication so please refer to the links at the end of the article for the current state of browser support.

New input types

HTML5 introduces no less than a baker’s dozen (yes, that’s 13!) new input types for forms. We’re going to take a brief look at each of them and explain why you should be using them right now. These new input types have dual benefits: using them means less development time and an improved user experience. The new input types we’ll be looking at are:

email

In rendering terms, the email input type is no different than a standard text input type and allows for one or more e-mail addresses to be entered. Combined with the required attribute, the browser is then able to look for patterns to ensure a valid e-mail address has been entered. Naturally, this checking is rudimentary, perhaps looking for an @ character or a period (.) and not allowing spaces. Opera 9.5+, Firefox 4+, Internet Explorer 10 and Chrome 5+ have already implemented this basic validation. The browser goes as far as presenting the user with an error message (see Opera in Figure 3) if the e-mail address entered isn’t valid. You can style the field for when an value is entered using the :valid, :invalid or :required pseudo class (assuming you have the required attribute on the input) just like Locum Dr. Peter explained.

<input type="email" name="email" required>
Screenshot of an email input field in Opera with an error message stating 'Please enter a valid email address' with 'gordo' written in the field
Figure 3. Opera e-mail address error messaging

The specification details that one or more e-mail addresses are allowed. This means that the multiple attribute could be used with type="email" too.

Pretty cool, huh? Again, this highlights how HTML5 forms help to cut down the amount of JavaScript that you have to write when carrying out form validation.

There’s always a catch, though, right? At the time of writing, there is an internationalization issue with type="email". When using it with double-byte internationalized domain names, the browsers invalidate them; so this example

<input type="email" name="email" value="gordo@日本.jp">

isn’t valid in Firefox, Safari, or Chrome (there is no issue in Opera). However, a workaround has been created by Kyle Barrow that uses type="text" with the pattern attribute, as shown here:

<input type="text" name="email" value="gordo@日本.jp" pattern="[^ @]*@[^ @]*">

An alternative solution is to continue using type="email" with the formnovalidate attribute on the submit button, as follows. This ensures that no validation will be carried out on form submission, which may or may not be suitable for your needs.

<form action="process.php">
<label for="email">Email:</label>
<input type="email" name="email" value="gordo@日本.jp">
<input type="submit" formnovalidate value="Submit">
Or you could use the novalidate attribute on your form, like so:

<form action="process.php" novalidate> <label for="email">Email:</label>
<input type="email" name="email" value="gordo@日本.jp">
<input type="submit" value="Submit">

Internationalization issues aside, remember how we said there are dual benefits to HTML5’s input types—less development time and better user experience? Let’s go back and look at the iPhone once more, as shown in Figure 4.

Screenshot of an iPhone with dynamic keyboard and the action button saying 'Go' when focussed on the email input field
Figure 4. The iPhone displays a custom keyboard when using type=”email”.

Did you notice it this time? No? Look at the keyboard again. That’s right, the keyboard is different. There are dedicated keys for the @ and . characters to help you complete the field more efficiently. As we discussed with type="search", there is no downside to using type="email" right now. If a browser doesn’t support it, it will degrade to type="text". And in some browsers, users will get a helping hand.

url

The url input type, as you might expect, is for web addresses. You can use the multiple attribute to enter more than one URL. Like type="email", a browser will carry out simple validation on these fields and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces, and possibly detecting a valid top-level domain (such as .com or .co.uk). Use the url input type like so:

<input type="url" name="url" required>

Again, we’ll take a look at how the iPhone renders type="url". As you can see in Figure 5, it has again updated the onscreen keyboard to ensure that completing the field is as simple as possible for the user by swapping the default space key for period, forward slash, and .com keys. (To access more endings like .org and .net, tap and hold the .com key.)

Screenshot of an iPhone with dynamic keyboard and the action button saying 'Go' when focussed on the URL input field
Figure 5. type=”url” activates a URL-specific keyboard on the iPhone.

tel

tel differs from email and url in that no particular syntax is enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered. It’s possible that you can validate specific phone numbers (if you can guarantee the format) using client-side validation. type="tel" is marked up as follows:

<input type="tel" name="tel" id="tel" required>

Once more, the iPhone recognises type="tel", only this time it goes one step further and completely changes the keyboard to the standard phone keyboard, as shown on the left in Figure 6. In addition to the iPhone, some Android devices (such as HTC Desire, shown on the right in Figure 6) also display a numeric keyboard for type="tel". That’s pretty handy, don’t you think? Nice, big keys for entering a phone number help you to get that big, nasty form completed quickly.

Screenshot of an iPhone and Android device with dynamic keyboard changing to a number input when the user is focussed on a tel input field
Figure 6. type="tel" on the iPhone and some Android devices dynamically changes the keyboard to a numeric keypad. (Android screenshot provided by Stuart Langridge).

number

number, as you might expect, is used for specifying a numerical value. As with the majority of these new input types, Opera was the first to implement type="number". It, Safari, and Chrome render the input as a spinbox control (see Figure 7) whereby you can click the arrows to move up or down. Or if you prefer, you can type directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type=”number” is in IE 10 also, although if you enter a non-numerical character the field empties when focus is lost and no feedback is provided to the user.

Screenshot of the Opera browser rendering of a number input field for 'showe size' the value is 9 and there are up and down arrows to the right of the field.
Figure 7. type="number" in Opera

With the additional attributes min, max, and step we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). This example shows how these attributes work:

<input type="number" min="5" max="18" step="0.5" value="9" name="shoe-size">

In this example, min represents the minimum value the field will accept, and max represents the maximum value. If we reach the maximum or minimum value, the appropriate arrow on the spinbox control will be greyed out so you can no longer interact with it. step is the increment that the value should adjust up or down, with the default step value being 1. This means we can include negative values or step up in increments of 0.5 or 5. value is that attribute you’re used to from previous versions of HTML. Each of the attributes are optional, with defaults being set if they aren’t used.

In contrast to Opera’s implementation, the iPhone (Figure 8) and some Android devices (such as HTC Desire, shown on the right in Figure 6-13) simply render the field as a standard text box but optimize the keyboard for easy input.

Screenshot of an iPhone and Android device with dynamic keyboard changing to a number input when the user is focussed on a number input field
Figure 8. type="number" on iPhone and Android HTC Desire (Android screenshot provided by Stuart Langridge)

To make the iPhone render with the standard telephone keypad as we saw for type="text" Chris Coyier, of CSS Tricks devised a little hoax you can use. Rather than using type=”number”, use a standard type="text" input and add a pattern attribute that accepts only numbers, as shown below. This solution isn’t ideal but if you think it could be useful, Chris has put a short video together showing it in action.

<input type="text" pattern="[0-9]*" name="shoe-size">

Chris’ technique may soon become absolete though with the introduction of the inputmode attribute. The attribute, recently added to the specification will allow users to specify the type of input mechanism that is most useful for users. When implemented, you will be able to choose between numeric, latin, email, or kana input modes.

range

The range input type is similar to number but more specific. It represents a numerical value within a given range. Why the difference, I hear you cry? Because when you’re using range, the exact value isn’t important. It also allows browsers to offer a simpler control than for number. In Opera, Safari, Internet Explorer 10 and Chrome, type="range" renders as a slider (see Figure 6-14). When moving the slider in IE 10 a tooltip appears showing the current value. Additionally, in Opera, if the CSS defines the height greater than the width, the slider control will be rendered vertically as opposed to the standard horizontal rendering.

The following code shows how we might mark up our skill level on a scale of 1 to 100 by setting the min and max attributes (see Figure 9). We can also set the starting point for range using the value attribute.

<input id="skill" type="range" min="1" max="100" value="0">
Screenshot of the range input type for Flying Skill level as rendered by Opera.
Figure 9. type="range" in Chrome

Dates and times

If you’ve ever booked tickets online, you will have come across date pickers to help you quickly and easily choose the date you require. Perhaps you’ve even implemented a date picker on your own website. Generally, this is done using a JavaScript library such as jQuery, Dojo, or YUI. It can be a pain when you need to load a whole library and associated plug-ins just to implement a simple date picker. Well, with HTML5 we get that functionality baked into the browser. Not only that, but we don’t have to stop at just electing a single date; we can select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward.

<input id="dob" name="dob" type="date">

You can go a step further by using the min and max attributes to ensure the user can only choose from a specified date range.

<input id="startdate" name="startdate" min="2012-01-01" max="2013-01-01" type="date">

As with many of the other form implementations, Opera leads the way (support in other browsers is varied). Let’s take a look next at how browsers render these input types.

date

Figure 10 shows Opera 10.5’s rendering of type="date".

Screenshot of the date input type rendered by Opera. There is a dropdown for the date and a calendar widget shown.
Figure 10. type="date" in Opera 10.5

These date pickers aren’t restricted to desktop devices; some Blackberry devices and Chrome for Android render its internal date picker when used with type="date" (see Figure 11).

Screenshot of the date input type as rendered on a Blackberry. There are three spinners, one for day, one for month and another for year.
Figure 11. type="date" on Blackberry (screenshot provided by Terence Eden)

month

Next up, Figure 12 shows type="month", which might, for example, be used for a credit card expiry date.

<input id="expiry" name="expiry" type="month" required>
Screenshot of the month input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current month highlighted.
Figure 12. type="month" in Opera 10.5

week

You can also drill down to type="week". Notice how Opera highlights a specific week using the same date picker control, as shown in Figure 13.

<input id="vacation" name="vacation" type="week">
Screenshot of the week input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current week highlighted.
Figure 13. type="week" in Opera 10.5

time

You can see in Figure 14 that type="time" renders a spinbox similar to that used earlier for selecting the precise time.

<input id="exit-time" name="exit-time" type="time">
Screenshot of the time input type rendered by Opera. There is an input with a value of 14:10 and up and down arrows to the right of the input.
Figure 14. type="time" in Opera 10.5

datetime

We can combine the date and time by using type="datetime" for specifying a precise time on a given day, as shown in Figure 15.

<input id="entry-day-time" name="entry-day-time" type="datetime">
Screenshot of the datetime input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current day highlighted. There is an input with a value of 12:08 and up and down arrows to the right of the input along with the text 'UTC'.
Figure 15. type="datetime" in Opera 10.5

datetime-local

Finally, Figure 16 shows that we can achieve slightly more granular control by selecting a precise time on a given day with a local time zone variation using type="datetime-local".

<input id="arrival-time" name="arrival-time " type="datetime-local">
Screenshot of the datetime-local input type rendered by Opera. There is a dropdown for the date and a calendar widget shown with the current day highlighted. There is an input with a value of 17:08 and up and down arrows to the right.
Figure 16. type="datetime-local" in Opera 10.5

Date and time caveats

There are two caveats with these implementations. First, with the current implementation, it isn’t possible to type a date into the field (in all browsers). The date picker is keyboard accessible, though. However, we can foresee a potential issue; if implemented on a form that a data entry clerk regularly completes, they are likely to be quicker at typing the date than tabbing through with the keyboard or selecting from a date picker. Second, it isn’t possible to style the look of the date picker. We tend to think that this is a good thing, as users will receive a common experience across all websites they visit (provided they use the same browser all the time). Undoubtedly, though, corporations will require a branded date picker. Safari 5 and Chrome 5 have implemented these input types, but, unfortunately, they aren’t very user friendly. Dates have to be entered in the same format as the time element that we met earlier in the book. So for dates, the format would be YYYY-MM-DD, and for dates with time, a user would have to enter YYYYMM-DDT00:00Z, which is not very friendly at all.

As with the other new input types, if a browser doesn’t recognize them, it will simply default back to type="text" and let the user continue to use your JavaScript date picker.

color

The color input type is pretty self-explanatory: it allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker, which will either be native to the operating system or a browser’s own implementation. Opera 11 has implemented type=”color” with a simple color picker that offers a number of standard color choices or the option to select Other, which brings up the operating system color picker (shown on the right in Figure 17).

<input id="color" name="color" type="color">
Screenshot of the color input type as rendered by Opera. There is a colour dropdown which when clicked shows a range of colours with an 'other' button. The right shows the dialog box opened when the user clicks 'Other' which is a standard operating system color dialog.
Figure 17. type="color" in Opera on the left and the result of clicking Other shown on the right

In contrast, certain Blackberry devices have implemented the color input type that renders a color picker, as shown in Figure 18.

Screenshot of the color input type as rendered on a Blackberry. There is a colour spectrum with a hue box and a color preview alongside an 'OK' button.
Figure 18. type="color" on Blackberry (screenshot provided by Terence Eden)

Input types summary

By using HTML5’s new form input types right now, we can enhance the user’s experience, future-proof our site, and make our life as developers easier. Obviously, we can’t just leave the browsers that don’t support all these new features hanging, and in Chapter 6 of Beginning HTML5 and CSS3 we take a look at how to detect support for these form features using JavaScript.

You can find a dummy form, using some of the examples we’ve shown in this article at our HTML5 forms demo page.

We’ve hinted throughout the article at which browsers have support for HTML5 forms input types and attributes. With new versions of browsers being released at an ever-increasing rate, it can be difficult to keep up with what is or isn’t supported. If you want to keep an eye on the current progress, we suggest visiting When can I use … or FindMeByIP or Wufoo’s HTML5 forms research.

If you missed the first article in this series on HTML5 forms, why not read a brief History of HTML5 forms and learn all about the new attributes introduced.

Cover image of Beginning HTML5 and CSS3: The Web Evolved.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

HTML5 forms input types originally appeared on HTML5 Doctor on February 28, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/html5-forms-input-types/feed/ 21
HTML5 forms introduction and new attributes https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/ https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/#comments Tue, 26 Feb 2013 14:30:58 +0000 http://html5doctor.com/?p=5001 No doubt you interact with at least one form on the Web every day. Whether you're searching for content or logging in to your e-mail account or Facebook page, using online forms is one of the most common tasks performed on the Web. As designers and developers, creating forms has a certain monotony about it, particularly writing validation scripts for them. HTML5 introduces a number of new attributes, input types, and other elements for your markup toolkit. In this article we'll be focussing on the new attributes with a future article looking at the new input types.

]]>
No doubt you interact with at least one form on the Web every day. Whether you’re searching for content or logging in to your e-mail account or Facebook page, using online forms is one of the most common tasks performed on the Web. As designers and developers, creating forms has a certain monotony about it, particularly writing validation scripts for them. HTML5 introduces a number of new attributes, input types, and other elements for your markup toolkit. In this article we’ll be focussing on the new attributes with a future article looking at the new input types.

As we’ll see, these new features will go a long way toward making your life easier while delivering a delightful user experience. The best thing about all this? You can start using them now. We’ll start with a (very) brief history of HTML5 forms though.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

Note: As this article is a book excerpt, browser renderings of attributes and input types may have altered since the screenshots were taken. Additionally, browser support may have increased since publication so please refer to the links at the end of the article for the current state of browser support.

A history of HTML5 forms

The forms section of HTML5 was originally a specification titled Web Forms 2.0 that added new types of controls for forms. Started by Opera and edited by then-Opera employee Ian Hickson, it was submitted to the W3C in early 2005. The work was initially carried out under the W3C. It was then combined with the Web Applications 1.0 specification to create the basis of the breakaway Web Hypertext Application Technology Working Group (WHATWG) HTML5 specification.

Using HTML5 design principles

One of the best things about HTML5 forms is that you can use almost all of these new input types and attributes right now. They don’t even need any shivs, hacks, or workarounds. That isn’t to say they’re all “supported” right now, but they do cool things in modern browsers that do support them-and degrade gracefully in browsers that don’t understand them. This is thanks to HTML5’s design principles. In this instance we’re specifically referring to the principle of graceful degradation. In essence, this means that there’s no excuse for not using these features right now. In fact, it means you’re ahead of the curve.

HTML5 form attributes

There are 14 new attributes that we’ll be looking at in this article.

placeholder

First up is the placeholder attribute, which allows us to set placeholder text as we would currently do in HTML4 with the value attribute. It should only be used for short descriptions. For anything longer, use the title attribute. The difference from HTML4 is that the text is only displayed when the field is empty and hasn’t received focus. Once the field receives focus (e.g., you click or tab to the field), and you begin to type, the text simply disappears. It’s very similar to the search box you see in Safari (see Figure 1).

Screenshot of the browser search box in Safari with and without focus
Figure 1. Browser search box in Safari without and with focus

Let’s have a look at how to implement the placeholder attribute.

<input type="text" name="user-name" id="user-name" placeholder="at least 3 characters">

That’s it! We can hear you thinking, “What’s so great about that? I’ve been doing it with JavaScript for years.” Yes, that’s true. However, with HTML5, it’s part of the browser, meaning less scripting is required for a more accessible, cross-browser solution (even when JavaScript is disabled). Figure 2 shows the placeholder attribute working in Chrome.

Screenshot of an input field in Chrome with and without focus, so showing and not showing the placeholder
Figure 2. Placeholder attribute support in Chrome, unfocused and focused

Browsers that don’t support the placeholder attribute ignore it, so it won’t render. By including it, though, you’re providing an enhanced user experience for those users who have browser support and you’re “future proofing” your site. All modern browsers support placeholder.

Note: There is no official pseudo-class for styling placeholder text but both Mozilla (makers of Firefox) and WebKit offer vendor prefixed properties for styling (-mozplaceholder and –webkit-input-placeholder). This makes it safe to assume that a pseudo-class will become standard for styling placeholder text. For further detail there is a thread on the WHATWG mailing list about this topic.

autofocus

autofocus does exactly what it says on the tin. Adding it to an input automatically focuses that field when the page is rendered. As with placeholder, autofocus is something that we used JavaScript for in the past.

Traditional JavaScript methods do, though, have some serious usability problems. For example, if a user begins completing the form before the script loads, they will (jarringly) be returned to the first form field when the script is loaded. The autofocus attribute in HTML5 gets around this issue by focusing as soon as the document loads, without having to wait for the JavaScript to be loaded. However, we only recommend using it for pages whose sole purpose is the form (like Google) to prevent the usability issues.

It is a Boolean attribute (except if you are writing XHTML5; see the note) and is implemented as follows:

<input type="text" name="first-name" id="first-name" autofocus>

All modern browsers support the attribute and, like placeholder, browsers that don’t support the autofocus attribute simply ignore it.

Note: Several new HTML5 form attributes are Boolean attributes. This just means they’re set if they’re present and not set if they’re absent. They can be written several ways in HTML5.

autofocus
autofocus=""
autofocus="autofocus"

However, if you are writing XHTML5, you have to use the autofocus="autofocus" style.

autocomplete

The autocomplete attribute helps users complete forms based on earlier input. The attribute has been around since IE5.5 but has finally been standardized as part of HTML5. The default state is set to on. This means that generally we won’t have to use it. However, if you want to insist that a form field be entered each time a form is completed (as opposed to the browser autofilling the field), you would implement it like so:

<input type="text" name="tracking-code" id="tracking-code" autocomplete="off">

The autocomplete state on a field overrides any autocomplete state set on the containing form element.

required

The required attribute doesn’t need much introduction; like autofocus, it does exactly what you’d expect. By adding it to a form field, the browser requires the user to enter data into that field before submitting the form. This replaces the basic form validation currently implemented with JavaScript, making things a little more usable and saving us a little more development time. required is a Boolean attribute, like autofocus. Let’s see it in action.

<input type="text" id="given-name" name="given-name" required>

required is currently implemented only in Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+, so for the time being you need to continue writing a script to check that fields are completed on the client side in other browsers (*cough* IE!). Opera, Chrome, and Firefox show the user an error message (see Figure 3) upon form submission. In most browsers, the errors are then localized based on the declared language. Safari doesn’t show an error message on submit, but instead places focus on that field.

Screenshot from Opera showing an error message on an input field
Figure 3. Form field with required attribute displaying a browser-generated error message in Opera

The default rendering of “required” error messages depends on the individual browser; at present the error message bubble can’t be styled with CSS in all browsers. Chrome, however, does have a proprietary property that you can use to style the error bubble. Peter Gasston has written an article about the syntax. You can also style the input using the :required pseudo-class. An alternative is to override the wording and styling using the setCustomValidity() method in JavaScript. Importantly, don’t forget that this browser validation is no substitute for validating on the server as well.

pattern

The pattern attribute is likely to get a lot of developers very excited (well, as excited as you can get about form attributes). It specifies a JavaScript regular expression for the field’s value to be checked against. pattern makes it easy for us to implement specific validation for product codes, invoice numbers, and so on. The possibilities for pattern are wide-ranging, and this is just one simple example using a product number.

<label>Product Number:
<input pattern="[0-9][A-Z]{3}" name="product" type="text" title="Single digit followed by three uppercase letters."/>
</label>

This pattern prescribes that the product number should be a single digit [0-9] followed by three uppercase letters [A-Z]{3}. For more examples, the HTML5 Pattern website lists common regex style patterns to help get you started.

As with required, Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ are the only browsers with support for pattern at present. However, with the browser market moving at a fast pace, the others will soon catch up.

list and the datalist element

The list attribute enables the user to associate a list of options with a particular field. The value of the list attribute must be the same as the ID of a datalist element that resides in the same document. The datalist element is new in HTML5 and represents a predefined list of options for form controls. It works in a similar way to the in-browser search boxes that autocomplete as you type (see Figure 4).

Screenshot Google's autosuggest functionality in Safaris search box
Figure 4. Google search autosuggestions in Safari

The following example shows how list and datalist are combined (see Figure 5):

<label>Your favorite fruit:
<datalist id="fruits">
  <option value="Blackberry">Blackberry</option>
  <option value="Blackcurrant">Blackcurrant</option>
  <option value="Blueberry">Blueberry</option>
  <!-- … -->
</datalist>
If other, please specify:
  <input type="text" name="fruit" list="fruits">
</label>

By adding a select element inside the datalist you can provide superior graceful degradation than by simply using an option element. This is an elegant markup pattern designed by Jeremy Keith that adheres perfectly with HTML5’s principle of degrading gracefully.

<label>Your favorite fruit:
<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:
</datalist>
  <input type="text" name="fruit" list="fruits">
</label>

Browser support for list and datalist is currently limited to Opera 9.5+ (see Figure 5), Chrome 20+, Internet Explorer 10 and Firefox 4+.

Screenshot of the list attribute and datalist element in Opera
Figure 5. The datalist element rendered in Opera

multiple

We can take our lists and datalists one step further by applying the Boolean attribute multiple to allow more than one value to be entered from the datalist. Here is an example.

<label>Your favorite fruit:
<datalist id="fruits">
  <select name="fruits">
    <option value="Blackberry">Blackberry</option>
    <option value="Blackcurrant">Blackcurrant</option>
    <option value="Blueberry">Blueberry</option>
    <!-- … -->
  </select>
If other, please specify:
</datalist>
  <input type="text" name="fruit" list="fruits" multiple>
</label>

multiple isn’t exclusively for use with datalists, though. A further example for multiple might be for email addresses when sending items to friend or the attachment of files, as shown here:

<label>Upload files:
<input type="file" multiple name="upload"></label>

multiple is supported in Firefox 3.6+, Safari 4+, Opera 11.5+, Internet Explorer 10 and Chrome 4+.

novalidate and formnovalidate

The novalidate and formnovalidate attributes indicate that the form shouldn’t be validated when submitted. They are both Boolean attributes. formnovalidate can be applied to submit or image input types. The novalidate attribute can be set only on the form element.

An example use case for the formnovalidate attribute could be on a “save draft” button, where the form has fields that are required for submitting the draft but aren’t required for saving the draft. novalidate would be used in cases where you don’t want to validate the form but do want to take advantage of the more useful user interface enhancements that the new input types offer.

The following example shows how to use formnovalidate:

<form action="process.php">
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" formnovalidate value="Submit">
</form>

And this example shows how to use novalidate:

<form action="process.php" novalidate>
  <label for="email">Email:</label>
  <input type="text" name="email" value="gordo@example.com">
  <input type="submit" value="Submit">
</form>

form

The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner). Using form means that the element doesn’t need to be a child of the associated form and can be moved away from it in the source. The primary use case for this is that input buttons that are placed within tables can now be associated with a form.

<input type="button" name="sort-l-h" form="sort">

formaction, formenctype, formmethod, and formtarget

The formaction, formenctype, formmethod, and formtarget attributes each have a corresponding attribute on the form element, which you’ll be familiar with from HTML4, so let’s run through each of them briefly. These new attributes have been introduced primarily because you may require alternative actions for different submit buttons, as opposed to having several forms in a document.

formaction

formaction specifies the file or application that will submit the form. It has the same effect as the action attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). When the form is submitted, the browser first checks for a formaction attribute; if that isn’t present, it proceeds to look for an action attribute on the form.

<input type="submit" value="Submit" formaction="process.php">

formenctype

formenctype details how the form data is encoded with the POST method type. It has the same effect as the enctype attribute on the form element and can only be used with a submit or image button (type="submit" or type="image"). The default value if not included is application/x-www-formurlencoded.

<input type="submit" value="Submit" formenctype="application/x-www-form-urlencoded">

formmethod

formmethod specifies which HTTP method (GET, POST, PUT, DELETE) will be used to submit the form data. It has the same effect as the method attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").

<input type="submit" value="Submit" formmethod="POST">

formtarget

formtarget specifies the target window for the form results. It has the same effect as the target attribute on the form element and can only be used with a submit or image button (type="submit" or type="image").

<input type="submit" value="Submit" formtarget="_self">

Form attributes summary

We’ve looked at several new form attributes that help improve user experience and save you development time. There are some more new attributes to discuss, which are covered together with HTML5’s new input types in the next article in this series.

You can find a dummy form, using some of the examples we’ve shown in this article at our HTML5 forms demo page.

We’ve hinted throughout the article at which browsers have support for HTML5 forms input types and attributes. With new versions of browsers being released at an ever-increasing rate, it can be difficult to keep up with what is or isn’t supported. If you want to keep an eye on the current progress, we suggest visiting When can I use … or FindMeByIP or Wufoo’s HTML5 forms research.

Cover image of Beginning HTML5 and CSS3: The Web Evolved.

This is article is an excerpt from Chapter 6 of Beginning HTML5 and CSS3: The Web Evolved by Christopher Murphy, Oli Studholme, Richard Clark and Divya Manian, published by Apress.

HTML5 forms introduction and new attributes originally appeared on HTML5 Doctor on February 26, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/html5-forms-introduction-and-new-attributes/feed/ 22
Drag and Drop and Automatically Send to the Server https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/ https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/#comments Tue, 03 Apr 2012 13:30:17 +0000 http://html5doctor.com/?p=4500 I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

]]>
I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

I'll walk you through an example that you can play with: drag a file into the web page, and it'll be uploaded to the server instantly.

Tasks

Let's break this process down into specific tasks:

  1. Capture the drop event and read its data.
  2. Post that binary data to the server.
  3. Provide feedback on the progress of the upload.
  4. Optionally render a preview of what's being uploaded and its status.

To achieve all of this, we need the following HTML5 and non-HTML5 APIs:

  1. Drag and Drop
  2. FormData
  3. XHR progress event
  4. FileReader

Keep in mind that not all browsers support all of this technology today, but they're getting close. I just wanted to create a clear and complete tutorial on how to go the whole hog and upload that dropped file.

The end result: we're able to drop the file anywhere in the browser, we get a preview and progress of the upload, and it's a slick experience.

Drag and drop upload
Our drag-and-drop example page

Drag and Drop

Just as a forewarning, drag-and-drop has been known to be a bit of a killjoy. In fact, it's a nightmare, but I won't repeat what's been said before.

Our example is going to allow you to drag-and-drop a file anywhere within the browser. To achieve that, we need to attach our event listeners to the body or documentElement (i.e., the root HTML node). By listening on the documentElement, this code could be anywhere in the page, as documentElement will always exist. You can only listen on body once the <body> element has been encountered.

Here's the pattern of code we need to capture the drop event on the entire document:

var doc = document.documentElement;
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();
  this.className = '';

  // now do something with:
  var files = event.dataTransfer.files;

  return false;
};
Basic pattern for capturing drop events

I'm using the hover class so that I can toggle a tip explaining to the user that the file can be dropped on the page.

Inside the drop event, we can access the dropped files via event.dataTransfer.files.

An Alternative to Drag and Drop

Annoyingly, as I write this, I realise this combination of API requirements is currently only met by Chrome and Firefox. So, taking the test from Modernizr, we can test for support and provide our alternative:

var dndSupported = function () {
  var div = document.createElement('div');
  return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

if (!dndSupported()) {
  // take alternative route
}
Testing for drag-and-drop support

Instead of drag-and-drop, we can insert a file input element (I've given it an id of "upload"), and when its value is changed, the file can be scooped in:

document.getElementById('upload').onchange = function (event) {
  // `this` refers to the element the event fired upon
  var files = this.files;
};
An alternative to native drag-and-drop

You can see the equivalent is simply the files property of the HTMLInputElement object. This will give us access to the same file as the event.dataTransfer.files from the drop event.

Automatically Uploading the File

This is the neat bit, and it's painfully simple. We use a feature of the XHR2 spec: FormData. Once we create an instance of FormData, we can append items to it:

var formData = new FormData();
for (var i = 0; i < files.length; i++) {
  formData.append('file', files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

xhr.send(formData);
Creating and posting FormData

Yeah, that's it.†

Let's look at a couple of key things that are going on the above code.

formData.append('file', files[i]);

We're sending named parameters to our server, specifically an array of values called file. Obviously, you can call it what you want, but the file is the name your server will be looking for when it saves the uploaded file (or files).

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

If you're familiar with XHR, you'll notice we aren't listening to onreadystatechange, only onload — which is (in effect) a convenience function to let you know when the readyState is 4 (i.e., loaded!). You should still check and respond appropriately to the status code of the request to ensure it's 200 OK, rather than a 500 (internal server error) or 404 (not found) or anything else.

xhr.send(formData);

The nice trick here is that XHR has automatically set the encoding of the posted data to multipart/form-data. This encoding allows your server to read and save the files. It's like the encoding used when you send an attachment in an email.

Providing Feedback to the User

XHR2 now (flippin' finally) comes with a progress event. So if you're sending or retrieving a large file via XHR, you can tell the user how far along you are.

It's pretty simple. If you want to track the progress of the XHR request, listen to the progress event. One gotcha that caught me out for some time: I needed to track the progress of the upload, not the download. To do this properly, you need to listen for progress on the XHR upload object, as so:

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var complete = (event.loaded / event.total * 100 | 0);
    progress.value = progress.innerHTML = complete;
  }
};

xhr.onload = function () {
  // just in case we get stuck around 99%
  progress.value = progress.innerHTML = 100;
};
Providing feedback with XHR2's progress event

Note that instead of xhr.onprogress, we use xhr.upload.onprogess. When this event fires, we check that the event supports calculating the amount of data uploaded (the lengthComputable part), and then calculate the amount completed.

In my HTML, I'm using a <progress> element (similar to the <meter> element, but more semantically appropriate as we're presenting the progress of a task) to show the user how much of their file has been uploaded:

<progress id="progress" min="0" max="100" value="0">0</progress>

Note that I'm using innerHTML for browsers that don't yet support <progress>. Then with a dash of CSS-generated content, both the innerHTML and value of the progress can be the same (perhaps an over optimisation, but I was rather proud of myself at the time!).

And Finally, Rendering a Preview

As a nice addition, we'll give the user a preview of what we're uploading for them. It requires the File API — specifically the FileReader API.

As the drag-and-drop operation (or the input[type=file]) contains a file object, we can hand this over to the FileReader to get the contents of the file. If it's something like an image, we can get the Base64 data and give the user a preview. Or if it's text, we could render it in a <div>. The MIME type for the file is available as the type property on the file object.

So let's assume we only accept images. Here's the preview part that runs after the file has been received by the browser:

var acceptedTypes = {
  'image/png': true,
  'image/jpeg': true,
  'image/gif': true
};

if (acceptedTypes[file.type] === true) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    image.width = 100; // a fake resize
    document.body.appendChild(image);
  };

  reader.readAsDataURL(file);
}
Rendering a preview of an uploaded image

We create the FileReader and give it a file to read. In the above example, I've used readAsDataURL, but you can also read files in plain text and binary formats (as per the spec).

When the reader has read the file and the data is available, it fires the load event, which in turn creates our new image.

The result of the file read action is in the event.target.result property. In the case of the readAsDataURL, the value is along the lines of data:image/png;base64,ABC....

Using All the Tools in the Shed

This example may be a little contrived for the article that I wanted to write. I've used many different technologies to do something that's a fairly common pattern on the web. In fact, it was because I had trouble finding a definitive source on uploading to the actual server (except, of course, as I wrote this article I found this example from back in late 2010!).

Hopefully, you'll see how each bit of tech can work together to create an application, but equally I hope that you can see where this would work if none or just some of the technology wasn't available. Make sure you detect functionality. Make sure you provide fallbacks. Make sure you develop responsibly.

Here's the final drag-and-drop and upload demo for you to play with.

Drag and Drop and Automatically Send to the Server originally appeared on HTML5 Doctor on April 3, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/feed/ 41
CSS3 Pseudo-Classes and HTML5 Forms https://stevefaulkner.github.io/html5doctored/css3-pseudo-classes-and-html5-forms/ https://stevefaulkner.github.io/html5doctored/css3-pseudo-classes-and-html5-forms/#comments Tue, 28 Feb 2012 14:30:47 +0000 http://html5doctor.com/?p=4483 Guest Doctor Peter Gasston takes a look at how new CSS3 Pseudo-classes align perfectly with HTML5 Forms.

]]>
Hello! I’m Doctor Peter and I’m here to treat you with a dose of complementary CSS3. Don’t worry, this won’t hurt a bit.

Contrary to what HTML5 Please and the W3C would have you believe, CSS3 is not part of HTML5. “But this is HTML5 Doctor,” I imagine you saying. “Why are you talking about CSS3 here?” Well, I want to talk about a very specific part of CSS3, one that works in perfect tandem with HTML5, specifically with the new form functions that are available.

One of the killer features that HTML5 introduces is client-side form validation without using JavaScript. Now, I know the other doctors haven’t discussed this yet, and as I’m just a locum, you might feel as if I’m putting the cart before the horse (#mixedmetaphors), but I’m hoping to explain just enough to let you know how it works, and then your regular doctors can provide the details at a later date.

A Recap of Pseudo-Classes

A pseudo-class is information about an element that’s in the document tree but not available through any specified attributes. For example, the :first-child pseudo-class applies to elements which are the first child of their parents. You can get that information from the DOM tree, but there’s no first-child attribute.

In CSS2.1, there were a handful of pseudo-classes available, notably the link states (:link, :visited) and those of user actions (:active, :hover). In CSS3, that handful becomes a basketful, with pseudo-classes of structure (:nth-child, :nth-of-type), UI element (:enabled, :checked), and the ones we’ll look at now, of form validation.

Form Validation without JavaScript

So as I mentioned at the beginning, HTML5 introduces client-side form validation without the need for JavaScript. When you attempt to submit a form, your browser will validate all of the fields and return an error if any of the fields is incorrect. This will happen mostly automagically — provided your browser has the capability — and will look something like what’s shown in Figure 1:

Form with an invalid field and associated error message
Figure 1: A form validation error message

Those error messages are browser and OS specific, and hard to modify (which I documented on my blog), but you can change the way the errors appear on the elements themselves with the new validation pseudo-classes, which are part of the CSS3 Basic UI module.

I’ll cover current browser support as we go through the article, but in a nutshell:

  • Firefox and IE10 support some of it.
  • Opera and Chrome support all of it.
  • Safari supports all of it too, but form validation is disabled by default.

That being the case, I’d recommend using Chrome, Opera, or Safari to view the examples I’ll be showing you.

If you want to keep up to date with browser support for form validation, I suggest keeping an eye on When can I use.

So with all of the boring technical guff out of the way, let’s get on with the interesting technical guff and take a look at some examples of form validation.

Required and Optional Elements

One of the most common patterns of validation is that of mandatory (that is, required) values — the fields that the user must complete in order to progress. To mark a form element as mandatory, you need only add the required attribute to it:

<input type="text" required>

If you want to apply styles to this in order to show that requirement, you can use the new :required pseudo-class, which applies rules to any matched element which has the required attribute. For example, you may want to put an asterisk after the text of the label:

input:required + label::after { content: "*"; }

The exact rules you use depends on how you’ve marked up your document. The rule in this example is based on the markup having this structure:

<input type="text" required id="foo">
<label for="foo">Foo</label>

The opposite of required is, of course, optional. And wouldn’t you know it, we have a pseudo-class for that too, logically named :optional. It affects any form element that doesn’t have a required attribute. For example, you may want to make those have a lighter border:

input:optional { border-color: silver; }

You can see this in action in Figure 2, or take a look at a live example.

Required and optional form fields
Figure 2: Input fields styled with :required (top) and :optional (bottom)

Valid and Invalid Elements

There are other types of validation besides simply “required” or “optional”. You can use pattern matching, such as email address validation:

<input type="email">

If the user enters anything into the field, it has to match the pattern of an email address, or else it will be marked as invalid. (Of course, if it’s not required, then it can be left blank.)

You can style valid or invalid form elements using pseudo-classes called — wait for it — :valid and :invalid. Maybe you want add a symbol depending on the validation status:

input:invalid + label::after { content: ' ⨉'; }
input:valid + label::after { content: ' ✓'; }

Note that these will take effect as soon as the page loads, so you’ll probably want to use JavaScript to apply them only after submission, perhaps by adding a class to the form with JavaScript:

document.forms[].addEventListener('submit', function(e) {
  e.currentTarget.classList.add('submitted');
  // Your fallback form validation function
});

The exact script you use will vary, but however you do it, you can use that class to style the form elements, like so:

.submitted input:invalid + label::after { content: ' ⨉'; }

Figure 3 shows the output of this, and you can also see the live example.

Valid and invalid form fields
Figure 3: Showing the use of the :valid (top) and :invalid (bottom) pseudo-classes

Two extra things to note about this example: first, in order to use my own JavaScript, I’ve prevented the form from automatically validating by using the novalidate attribute on the submit button; and second, Firefox puts a coloured glow around elements depending on their validation state, which I’ve over-ruled by using their proprietary :-moz-ui-invalid selector. View the source of the demo to see how these are used.

Number Ranges

Some of the new input types, such as number, allow a range of values using the min and max attributes, like so:

<input type="number" max="10" min="1">

Although form controls will usually prevent the user from entering a value outside of this range, there may be occasions (such as when JavaScript is used to provide values) where the value provided to the input does exceed the range:

<input type="number" max="10" min="1" value="11">

When this happens, you can use the :out-of-range pseudo-class for your styling:

input[type='number']:out-of-range { border-color: red; }

And, as you’d expect, there’s a counterpart known by the name of :in-range:

input[type='number']:in-range { border-color: green; }

In Figure 4 you can see these two pseudo-classes at work, and once more there’s also a live example to view.

Out-of-range and in-range form fields
Figure 4: The :out-of-range (top) and :in-range (bottom) pseudo-classes applied to a range input

Reading and Writing

You may have a form field that’s pre-filled with a value that you don’t want the user to be able to edit, such as terms and conditions in a textarea. If that’s the case, you can add the readonly attribute:

<textarea readonly>Lorem ipsum</textarea>

You can style elements which have the readonly attribute applied, using…can you guess? You are correct, imagined reader: the :read-only pseudo-class. You could combine it with the user-select CSS property to prevent the user from being able to select the text (in the example, I’ve also changed the border style to make it more obvious):

textarea:read-only { user-select: none; }

And if you should need it, there is of course a :read-write pseudo-class for elements which don’t have the attribute applied:

textarea:read-write { user-select: text; }

You can see the results in Figure 5, and as before there’s a live example too.

Read-only and read-write form fields
Figure 5: The textarea on the left is styled using :read-write, and the one on the right, with :read-only

Firefox and IE10 have actually implemented the readonly attribute, but don’t yet have support for these pseudo-classes.

Browser Support

This table lists support for HTML5 Form Validation in browsers at the time of writing:

Browser support for HTML5 Form Validation
Browser/Attribute Chrome Firefox IE Opera Safari
:optional / :required 10.0 4.0 10.0 10.0 5.0
:invalid / :valid 10.0 4.0 n/a 10.0 5.0
:in-range / :out-of-range 10.0 n/a n/a 10.0 5.0
:read-only / :read-write 10.0 n/a n/a 10.0 5.0

That’s All from Me

I hope I’ve given you enough to whet your appetite for finding out more about HTML5 Form Validation. There’s plenty more to it, including a full JavaScript API (you can read about this in the HTML5 spec, but ).

Thanks for your time, and thanks to the Doctors for this opportunity.

CSS3 Pseudo-Classes and HTML5 Forms originally appeared on HTML5 Doctor on February 28, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/css3-pseudo-classes-and-html5-forms/feed/ 38