Формы в сети. Они буквально повсюду, и, кажется, для них действительно есть все виды ароматов. С первого дня они стали отличным средством для ввода данных и информации и взаимодействия с различными службами. И все, что приходит с этим, — это каждая реализация под солнцем, которая предлагает для них проверку, настраиваемое отображение и функциональность, если они не встроены в этот конкретный веб-браузер, и многое другое. Поэтому на этапе разработки HTML5 одной из важных вещей, которые были рассмотрены, является превращение форм в Интернете в то, что и конечным пользователям, и разработчикам необходимо для упрощения работы. Зачем каждому веб-разработчику снова придумывать колесо или включать тонны JavaScript-кода просто для того, чтобы сделать что-то очень простое, например, средство выбора даты?
Давайте оставим это позади и рассмотрим все новые дополнения к формам в HTML5!
Существуют пять основных улучшений, когда речь заходит о возможностях форм в HTML5:
- Новые типы ввода
- Новые атрибуты
- Новые элементы
- Проверка
- API, такие как File API
В этой статье я расскажу о первых трех из них и о том, что это значит для вас как веб-разработчика. Я планирую продолжить с другой статьей о том, как создавать скрипты для форм с новыми имеющимися у нас опциями, а также освещать валидацию и выбранные API.
Новые типы ввода
Это новые типы ввода в HTML5. Некоторые из них напрямую связаны, чтобы определенным образом отображаться в веб-браузере, в то время как другие больше предназначены для семантической ценности и / или связаны с их проверкой. Отличительной особенностью типов ввода также является то, что, если они не поддерживаются в веб-браузере, по умолчанию они возвращаются к обычному элементу <input type = ”text”>: без ошибок, без обработки нескольких версий кода.
Вот новые типы ввода:
-
Цвет
Предоставляет конечному пользователю палитру цветов для выбора цвета.
-
date
Предлагает datepicker.
-
datetimeЭлемент для выбора даты и времени.
-
datetime-localЭлемент для выбора даты и времени с поддержкой локальных настроек.
-
emailПоле для ввода адреса электронной почты.
-
месяцВыберите полный месяц.
-
номерВыбор номера.
-
диапазонПредлагает ползунок для установки определенного значения / позиции.
-
searchПоле для поисковых запросов.
-
телВыбор номера телефона.
-
ВремяВведите определенное время.
-
urlВвод URL.
-
неделюВыбор конкретной недели.
Примеры
Примеры этих новых типов ввода, с образцом или ожидаемым значением (или считанным значением после отправки формы), установленным в их соответствующем атрибуте значения:
<input type="color" value="#b97a57">
<input type="date" value="2011-06-08">
<input type="datetime" value="2011-06-09T20:35:34.32">
<input type="datetime-local" value="2011-06-09T22:41">
<input type="email" value="[email protected]">
<input type="month" value="2011-06">
<input type="number" value="4">
<input type="range" value="15"> <!-- Note: If not set, default attribute values are min="0", max="100", step="1". -->
<input type="search" value="[Any search text]"> <!-- Note: In WebKit-based web browsers (Google Chrome, Safari) you can add the non-standard results attribute to get a looking glass icon to click to see the latest searches, and the attribute autosave to keep them across page loads. -->
<input type="tel" value="[Any numeric value]"> <!-- Note: Most web browsers seem to let through any value at this time. -->
<input type="time" value="22:38">
<input type="url" value="http://robertnyman.com"> <!-- Note: requires a protocol like http://, ftp:// etc in the beginning. -->
<input type="week" value="2011-W24">
Demo page
You can see all of these new input types in action with their code listed below at HTML5 Forms input types demo.
New attributes
To complement the new input types, there are a number of new attributes for actions web developers often need:
-
autocomplete
An option to turn off automatic form completion of values for a field. Possible values are “on” and “off”.
-
autofocusWhether focus should be set to this field as soon as it has loaded.
-
formactionFor buttons that submit a form (e.g. <input type=”submit”>, <input type=”image”> and <button> elements) to be able to override the action attribute of the form; for
instance if different buttons should submit the form to different URLs. No more JavaScript to do this!
formenctype
For buttons that submit a form to be able to override the form’s specified encoding
-
formmethodFor buttons that submit a form to be able to override the form’s method attribute, in case a button should change the method.
-
formnovalidateAppend to a submit button to bypass form validation.
-
formtargetFor buttons that submit a form to be able to override the form’s target attribute.
-
listTo connect with a <datalist> element by its id, to use its <option> elements as suggestions.
-
maxMaximum value for the value that can be put in.
-
minMinimum value for the value that can be put in.
-
multipleAllows for selection of multiple files for <input type=”file”> elements, and for multiple e-mail addresses separated by a comma.
-
novalidateApplies only to the <form> element, and prevents a form from being validated before submitted.
-
patternDeclaring what pattern should be used for validating a field’s value, in the form of a regular expression.
-
placeholderMeant to be able to display a hint to the end user what to input. (Side note: I wrote
a blog post discussing the desired behavior of the placeholder attribute) -
readonlyIf a field should be readonly.
-
requiredFor validation purposes, if a field is required or not.
-
spellcheckLets the web browser know if it should spell check the contents or not.
-
stepPossibility to control the size of each step for elements that accepts number or date input.
Examples
Examples of the new attributes:
<input type="text" autocomplete="off">
<input type="text" autofocus>
<input type="submit" formaction="http://example.org/save" value="Save">
<input type="submit" formenctype="application/x-www-form-urlencoded" value="Save with enctype">
<input type="submit" formmethod="POST" value="Send as POST">
<input type="submit" formnovalidate value="Don't validate">
<input type="submit" formtarget="_blank" value="Post to new tab/window">
<input type="text" list="characters"> <!-- Note: See a complete example in the New elements section below. -->
<input type="range" max="95">
<input type="range" min="2">
<input type="file" multiple>
<form action="http://example.org" method="GET" novalidate>
<input type="text" pattern="[A-Z]*"> <!-- Note: It is case sensitive, so you need to supply both lower- and upper-case letters if you want to allow that. -->
<input type="placeholder" name="first-name" placeholder="E.g. John Locke">
<input type="text" readonly>
<input type="text" required> <!-- Note: Some web browsers have to have a name attribute for this to work (this could also apply to other HTML5 Forms features, so pro tip is to always have a name attribute for form elements). -->
<input type="text" spellcheck="true"> <!-- Note: Has to be set to true or false, just an attribute present doesn't work -->
<input type="number" step="3">
Demo page
You can see all of these new attributes applied to form elements in the HTML5 Forms attributes demo.
New elements
-
datalist
Contains a number of <option> elements with values that can be used as suggestions for other form elements through the usage of the list attribute on them.
-
keygenOffers a way to create a public/private key pair where the public key is sent with the form. (Ok, I’ll be honest – probably not the new element that will get you the most excited… Also it seems like Internet Explorer are not interested in implementing it either)
-
meterThe meter element is for displaying values on a bar, where you can custom control min, max and assigned value. You can also specify low, high and optimum to set up different kind of areas of the bar.
-
outputDedicated to output the result of a calculation in the page, for instance sliding a <input type=”range”> back and forth.
-
progressMeant to be used to indicate progress of any kind in a web page, for instance file upload progress.
Examples
Example code of using these elements:
Note that the value attribute is the value being read out for its connected <input> element. In some web browsers, the inner text of the <option> element, if set, overrides the value attribute; in other web browsers only the value attribute is taken into consideration. So the best way to make it work is using the value attribute for suggestions.
<input type="text" name="characters" list="data-list"> <datalist id="data-list"> <option value="Hugo Reyes"> <option value="Jack Shephard"> <option value="James 'Sawyer' Ford"> <option value="John Locke"> <option value="Sayid Jarrah"> </datalist>
<keygen name="key"></keygen>
Important to note for the <output> element is that support for the JavaScript event oninput for the <form> element is required (it used to be an onforminput event on the <output> but that has now been deprecated). The code in the example below detects whether there is existing support for the oninput event, and if yes, applies an event handler that updates the value of the <output> element according to the value set for the <input type=”range”> element.
<meter min="0" max="10" value="7"></meter> <input type="range" id="range" name="range"> <output for="range" id="output"></output> <script> (function () { var theForm = document.getElementById("the-form"); if ("oninput" in theForm) { theForm.addEventListener("input", function () { output.value = range.value; }, false); } })(); </script>
<progress max="100" value="70">70%</progress>
Demo page
All the new elements are available to test in the HTML5 Forms elements demo.
Web browser support
As you can imagine, web browser support for such a vast amount of different features is varying. Another factor that plays in is that there’s room for interpretation in the specifications how some form elements should be displayed, and the expected behavior of them. There are a few compatibility lists that I like and I recommend taking a look at:
However, I strongly urge you to test as much as possible yourself. Things are changing constantly when it comes to web browsers nowadays (about time, right?) and not all test tables will be up to date. It could also be that a web browser claims to support something when tested with feature detection, but in reality it doesn’t work. Or, it works, but the user experience is not the one you want to convey.
So code like crazy, but evaluate the result of your code and how end users will perceive it: after all, we do this to give them the best experience!
Mobile improvements
One important thing to also bear in mind is with myriad of mobile devices, tablets et al, is that while there might not necessarily be support for a certain input type, by using it, it could trigger the most appropriate keyboard layout to make inputting information as smooth as possible for the end user. This means a number keyboard layout for <input type=”number”>, URL layout for <input type=”url”> etc.
Downside: styling
While we have an abundance of new features for forms in HTML5 and CSS3 pseudo-classes for styling elements (e.g. :valid, :invalid, :required), one of the major shortcomings is that there are very few ways to style the native controls like datepicker, range, validation messages etc. And sure, we could argue that it’s great for end users if form elements look the same across all web sites, to give them the soothing calm of consistency.
But there are two important reasons why that will never suffice:
- The styling supplied for various form elements always seem to be a bit of a low priority when they surface, and over time they get better. But many people believe that the design of form elements leave a lot to desire.
- Web sites will always have the need to make the design consistent with the rest of the web site, for a better user experience and for branding. This is inevitable, and if we don’t provide it for them for HTML5 Form elements, they will very likely go back to using JavaScript-powered solutions for all of the above, and I don’t believe anyone really gains from that.
At the time of writing, there a few ways you can style HTML5 Form elements in WebKit, in this fashion:
/* Remove default input type="search styling */ input[type="search"] { -webkit-appearance: textfield; /* You could also use none */ }
/* Style placeholder text */ input::-webkit-input-placeholder { color: #ffffa2; }
There are a bunch more, and you are interested, you can read up on them in Styling Form Controls Using Pseudo Classes. Do beware that this is not standard, and that they might change over time (but hey, if you have a deadline now, who cares? .
There have also been suggestions mentioned by Peter Gasston on how we could add some new CSS pseudo-classes to handle this. For example:
/* Note that this is not valid CSS code and won't work anywhere */ input::error { position: below; }
Do something formtastic!
As you can see with all the new input types, attributes and elements, a lot of the things we spent countless hours on implementing before will be native in web browsers, saving us a lot of work and offering users something extremely well tested and implemented. With HTML5 really comes a revolution on the web with open standards to try and meet all the needs of developers, and it is all implemented in a very fast pace.
I’d like to urge you to use these new HTML5 Forms features, be it just for some more semantic value or for offering a lot of the new functionality as well. They are here to make things better for you, so evaluate them, learn their tricks and tweaks, and make sure to let your feedback go to web browser vendors and specification writers, so they can ensure that they will meet the needs of the development community.
Now go do something formtastic!