Introduction to HTML5 forms and new attributes. HTML tag attributes Basic html attributes

We've already figured it out. We found out that they have content. However, that's not all. Tags also have attributes that enhance their capabilities, and attributes in turn have values. With their help, you can set parameters for an element and determine the design style. For example, with the tag

you have marked the paragraph. But how to make it aligned to the right? To do this, you will need a specific attribute with the corresponding value. Just as some tags do not have a pair, some attributes can be used without values.

How to write attributes?

Attributes are reserved words (like tags, only without angle brackets), but their meanings can be different. Just like tags, it is recommended to write attributes with values ​​in small letters, although browsers, in general, do not care - this is just a rule of good manners: in Russian, it is ALSO NOT ACCEPTABLE TO WRITE WHEN CAPS LOCK IS ENABLED. Why is HTML worse?

Attribute values ​​are written in the following format:

Attribute=”value” lang=”en”

You should always write attributes inside the opening tag, after the reserved word.

Paragraph

Typically there are multiple attributes available for a single tag. It doesn't matter in what order they are listed.

Universal attributes

Each HTML tag has its own set of attributes. Some attributes may be available for multiple tags, while others may only work with one. There is also a group of universal (global) attributes that can be used with any tag. Let's briefly look at the attributes of this category.

  • accesskey allows you to set a keyboard shortcut to access a specific page object. For example, you can make sure that the user uses the Alt+1 key combination to follow a specific link. Thus, develop a key navigation system.

The attribute value can be numbers 0-9 or letters of the Latin alphabet:

The link will be opened by pressing the key combination with one

  • class allows you to associate a tag with a predefined s using CSS design. Using an attribute allows you to significantly reduce the code, because instead of repeating the same CSS block, you can simply enter the name of the corresponding class.
  • Using contenteditable, you can allow the user to edit any element of the HTML page: delete, insert, change text. The same attribute makes it possible to edit and disable. It has only two values: true - allow editing, false - disable.
  • Using the contextmenu attribute, you can provide any document element with unique context menu items at your discretion. The menu itself is created in the tag, and the contextmenu attribute is assigned its identifier.
  • dir specifies the direction of the text: left to right (ltr) or right to left (rtl).
  • draggable allows you to disable (false) or allow (true) the user to drag a page element endowed with this attribute.
  • dropzone tells the browser what to do with the dropped element: copy (value copy), move (move) or create a link to it (link).
  • hidden - an attribute that allows you to hide the content of an element so that it is not displayed in the browser. If the attribute is set to false, the object is displayed, true - it is hidden.
  • id specifies the identifier of the element - a kind of name that is needed to simply change the style of the object, as well as so that scripts can access it. The value of the attribute will be its name. It must begin with a Latin letter, and can contain numbers, letters of the same Latin alphabet (large and small), as well as hyphen (-) and underscore (_) symbols. Cannot contain Russian letters.
  • lang helps the browser understand what language the content is written in and style it accordingly (for example, languages ​​may use different quotes). The values ​​are language codes (Russian - ru, English - en, etc.).
  • spellcheck enables (true) or disables (false) spell checking. It is especially useful to use the attribute in form field tags where the user will enter text.
  • style allows you to set the design of an element using CSS code.
  • tabindex allows you to determine how many times the user will have to press the Tab key for an object with that attribute to receive focus. The number of clicks determines the attribute value - a positive integer.
  • title - a tooltip that will appear if you move the mouse over an element and leave it motionless for a while. The line in the meaning will be a hint.
  • translate allows (yes) or denies (no) translation of the tag contents.
  • align specifies the element's alignment. For example, you can use it to align text to the left (left), right, center, or justify. For images (tag ) it is also possible to align to the top border of the highest element of the line (top), to the bottom border (bottom), and the value middle makes the middle line of the image coincide with the baseline of the line.

It is worth keeping in mind that using the align attribute is not recommended, and it is better to align text using CSS.

Example of using attributes

As an example, consider the line of HTML code:

This text can be edited

The entire line creates a paragraph of text that the user can edit in the browser.

Let's look at each element of the line.

- the opening tag of the container storing the paragraph.

- closing tag.

Between the symbols > and< расположен текст Этот текст можно редактировать. Это - надпись вне тегов (между ними), а значит она будет видна открывшему страницу пользователю. Браузер воспринимает её как простой текст, который надо вывести на экран.

contenteditable =”true” - this is the attribute and its value. Remember how in school: x=3. Same here: contenteditable = “true”. The contenteditable attribute specifies whether the user can edit the content of the element; the value true , written in quotes separated by an equal sign, allows editing:

Attribute=”value” contenteditable=”true”

Last update: 04/08/2016

Before moving directly to creating your web pages in HTML5, let's look at the basic building blocks that make up a web page.

HTML5 document, like any other HTML document, consists of elements, and elements consist of tags. Typically, elements have an opening and closing tag, which are enclosed in angle brackets. For example:

div element text

A div element is defined here, which has an opening tag and a closing tag. Between these tags is the content of the div element. In this case, the content is the simple text "Text of the div element".

Elements can also consist of a single tag, for example, element
, whose function is to break a line.

Text
div element

Such elements are also called empty elements. Although I used a closing slash, its presence is optional according to the specification, and is equivalent to using a tag without a slash:

Each element inside the opening tag can have attributes. For example:

Button

There are two elements defined here: div and input. The div element has a style attribute. After the equal sign, the attribute value is written in quotes: style="color:red;" . In this case, the value is "color:red;" indicates that the text color will be red.

The second element - the input element, consisting of one tag, has two attributes: type (indicates the type of element - button) and value (defines the text of the button)

There are global or common attributes for all elements, such as style, and there are specific ones that apply to certain elements, such as type.

In addition to regular attributes, there are also Boolean attributes. Such attributes may not be meaningful. For example, you can set the disabled attribute for a button:

The disabled attribute indicates that the element is disabled.

Global attributes

HTML5 has a set of global attributes that apply to any HTML5 element:

    accesskey : defines the key for quick access to element

    class : specifies the CSS class that will be applied to the element

    contenteditable: determines whether the element's content can be edited

    contextmenu : defines context menu for an element that is displayed when you click on the element right click mice

    dir: sets the direction of text in an element

    draggable: determines whether the element can be dragged

    dropzone: determines whether drop zone data can be copied when dropped onto an element

    hidden : hides the element

    id : The element's unique identifier. Elements on a web page should not have duplicate identifiers

    lang : specifies the language of the element

    spellcheck : indicates whether there will be for of this element spell checker used

    style : sets the style of the element

    tabindex : Defines the order in which items can be toggled using the TAB key

    title : sets an additional description for the element

    translate : determines whether the element's content should be translated

But, as a rule, from this entire list, three are most often used: class, id and style.

Custom Attributes

Unlike previous version custom attributes have been added to the markup language in HTML5. Now the developer or creator of the web page can define any attribute by prefixing it with a prefix data-. For example:

The data-color attribute is defined here and has the value "red". Although there is no such attribute for this element, nor in html in general. We define it ourselves and set it to any value.

Single or double quotes

You can often find cases where both single and double quotes are used in html when defining attribute values. For example:

Both single and double quotes are acceptable in this case, although double quotes are more often used. However, sometimes the attribute value itself may contain double quotes, in which case it is better to put the entire value in single quotes:

On HTML5, although all modern browsers already support this standard. As of December 2011, the standard is still under development.

HTML5 adds many new syntactic features - , , and . These elements are designed to make it easier to embed and manage graphics and media on the web without having to resort to native plugins and APIs. Other new elements such as , , and are designed to enrich the semantic content of the document (page).

New HTML5 tags
  • 1. Section tags (article, aside, footer, header, hgroup, nav, section)
  • 2. Content grouping tags (figure, figcaption)
  • 3. Tags for semantic text highlighting (bdo, mark, time, ruby, rt, rp, wbr)
  • 4. Tags for inserting content (audio, video, canvas, embed, source)
  • 5. Tags for form elements (datalist, keygen, output, progress, meter)
  • 6. Interactive elements (details, summary, command, menu)
Tag Brief description
Defines an article
Defines content aside from the main page content
Defines audio content
Defines graphics
Defines a command button
Defines data into an ordered list
Defines a dropdown list
Defines a data template
Defines element details
Defines dialogue (conversation)
Defines the purpose of the event sent across the server
Defines a group of media content, and their captions
Defines a footer for a section or page
Defines the section or page title area
Defines selected text
Defines measurements within a predefined range
Defines navigation links
Defines a nested point in a data pattern
Defines some types of result
Determines the progress of a task of any kind
Defines rules for updating templates
Defines a section (section)
Defines media resources
Defines date/time
Defines video
Unsupported tags: Tag Brief description
Not supported.
Defines an acronym
Not supported.
Defines an applet
Not supported.
Using instead of CSS to set the font
Not supported.
Defines large text
Not supported.
Defines the search index in a document
Not supported.
Defines a section that does not support a frame
Not supported.
Not supported.
Defines strikethrough text
Not supported. Defines TTY text
Not supported. Defines underlined text
Not supported.
Defines aligned text
List of HTML5 attributes Attribute Value Brief description contenteditable
true Defines underlined text
false
Determines whether the user can edit the content (content)
contextmenu
menu_id Defines underlined text
Not supported.
Defines the context menu of an element
draggable false auto
Determines whether the user can drag an element irrelevant Specifies that the element has no value. The element having a value is not displayed
ref false URL/id
Defines a link to another document/part of a document (only used when the attribute value is set)

registrationmark

reg_mark

Specifies the registered sign of an element

template

Defines a link to another document/part of a document that should be applied to the element HTML5 Page Layout Structure When using the usual website page structure, you can identify several typical blocks, described by a div tag with the corresponding class (, , , , etc.).

Author's note: There's no doubt that you interact with at least one form online every day. Whether you're searching for content or logging into your Facebook page, using online forms is one of the most common tasks on the web. For designers and developers, creating forms is somewhat monotonous, especially writing data validation scripts for them. HTML5 introduces many new attributes, input types, and other markup tooling elements.

In this article we'll focus on exploring new attributes, and in the next we'll look at data entry types.

It will be seen that the new features will make our life much easier when impressing users. What's the most attractive thing here? You can use them now. We'll start with a very brief history HTML5 forms.

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

Note: Because this article is an excerpt from a book, the browser's handling of attributes and input types may have changed since the screenshots were taken. In addition, browser support may have expanded since publication, so please refer to the links at the end of the article regarding its current status.

History of HTML5 Forms

The forms section of HTML5 was originally a specification called Web Forms 2.0, which added new types of form management tools. Started at Opera and edited by then-Opera staff member Ian Hickson, it was approved by the W3C in early 2005. The work was originally conducted by the W3C. It was then merged with the Web Applications 1.0 specification to form the basis of the breakaway HTML5 specification working group Web Hypertext Application Technology Working Group (WHATWG).

Applying HTML5 Design Principles

One of best characteristics HTML5 forms mean that almost all new data entry types and attributes can be applied immediately. They do not require any additional chips, hacks or other patches. It's not that they're all "supported" yet, but in modern browsers that actually support them, they can do cool things - and degrade beautifully in browsers that don't understand them. All this is thanks to the design principles of HTML5. In this case, we specifically refer to the principle of beautiful degradation. Overall, it would be unforgivable not to start using these features right away. In fact, this will mean that you are ahead of the rest.

HTML5 Form Attributes

In this article, we'll look at the following 14 new attributes.

placeholder

The first is the placeholder attribute, which allows us to set placeholder text, which until recently was done in HTML4 using the value attribute. It can only be used for short descriptions. For longer ones, use the title attribute. The difference with HTML4 is that the text is only shown when the field is empty and not in focus. As soon as the field comes into focus (for example, by clicking the mouse or pointing at the field) and you start typing, the text simply disappears. Very similar to the search field in Safari.

Let's figure out how to implement the placeholder attribute.

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

Like this! I can hear you thinking, “What’s so special about him? I've done this all my life in JavaScript." Yes, that's right. However, with HTML5 it becomes part of the browser, meaning less script needs to be written to achieve a more accessible cross-browser experience (even with JavaScript disabled). The figure shows how the placeholder text attribute works in Chrome.

Browsers that don't support the placeholder attribute will ignore it, so it won't be executed. However, by turning it on, you improve the experience for those whose browsers support it, and also ensure that your site is future-proof. All modern browsers support placeholder text.

autofocus

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

However, traditional JavaScript methods have serious usability problems. For example, if the user starts filling out a form before the script has fully loaded, it will (unpleasantly) return after loading to the first form field. The autofocus attribute in HTML5 gets around this problem by focusing as the document loads, without having to wait for JavaScript to load. However, we recommend using it to prevent usability problems only for those pages whose sole purpose is a form (like Google's).

This is a boolean attribute (unless you are writing XHTML5; see note) and is executed like this:

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

All modern browsers support it and, like a placeholder, browsers that don't autofocus simply ignore it.

Note: Some new HTML5 form attributes are booleans. This simply means that they are installed if present, and not installed if missing. In HTML5 they can be written in several ways different ways.

autofocus autofocus="" autofocus="autofocus"

autofocus

autofocus = ""

autofocus = "autofocus"

However, when writing XHTML5, you should use the autofocus="autofocus" style.

autocomplete

The autocomplete attribute helps users complete forms based on previous data entry. The attribute has been used since IE5.5, but was finally standardized as part of HTML5. By default it is active. This means that we generally won't have to use it. However, if you want to insist on typing into a form field every time you fill it out (as opposed to the browser auto-filling the field), then do it like this:

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

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

required

The required attribute does not require representation; like autofocus, it does exactly what you expect it to do. When you add it to a form field, the browser requires the user to enter data into that field before submitting the form. It replaces the basic form validation currently done with JavaScript, making everything more convenient and saving us some 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 >

Currently required is only implemented in Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+, so for the time being you will have to continue writing field validation scripts on the client side of other browsers (*cough cough* IE!). Opera, Chrome and Firefox show the user an error message when submitting a form. In most browsers, errors are then localized based on the declared language. Safari doesn't show an error message when submitting, but instead puts the field in focus.

The default display of the "required" error message varies by individual browser; The error bubble currently cannot be styled with CSS in all browsers. Chrome, however, has its own property that can be used to style the error message. You can also assign styles to your data input using the:required pseudo-class. An alternative is to override the wording and styles in JavaScript using the setCustomValidity() method. It is also very important not to forget that such browser-based validation does not replace server-side validation.

pattern

The pattern attribute is usually a big concern for many developers (well, as much as any form attribute). It defines JavaScript regular expression for the field whose value you want to check. Pattern makes it easier for us to apply separate verification for codes, account numbers, and so on. The possibilities of pattern are vast, and here is just one simple example using a product number.

Product Number:

< label >Product Number:

< input pattern = "{3}" name = "product" type = "text" title = "Single digit followed by three uppercase letters." / >

< / label >

This pattern dictates that the product number must be one digit followed by three capital letters (3). You can see more templates on the HTML5 templates website, which has a list of common regular expressions style templates to help you get started with them.

As with required, Opera 9.5+, Firefox 4+, Safari 5+, Internet Explorer 10 and Chrome 5+ are the only browsers that currently support templates. However, others will soon catch up due to the rapid advancement of the browser market.

list and datalist elements

The list attribute gives the user the ability to associate a list of options with a specific field. The value of the list attribute must be the same as the ID of a datalist element located in the same document. The datalist element is new to HTML5 and represents a predefined list of form control options. It works similarly to in-browser search fields, which automatically complete words as you type.

The following example shows how list and datalist combine.

Your favorite fruit: Blackberry Blackcurrant Blueberry If other, please specify:

< 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 to the datalist, you can achieve excellent degradation simply by applying an option element. Here's an elegant markup template created by Jeremy Keith that fits perfectly with HTML5's gradual degradation principles.

Your favorite fruit: Blackberry Blackcurrant Blueberry If other, please specify:

< 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+, Chrome 20+, Internet Explorer 10 and Firefox 4+.

multiple

You can take your list and datalist a step further by using the multiple boolean attribute so that you can enter more than one value from the datalist. Here's an example.

Your favorite fruit: Blackberry Blackcurrant Blueberry If other, please specify:

< 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 >

However, multiple is not used exclusively with datalist. A further example of using multiple would be addresses Email when forwarding items to a friend or attaching files, as shown here:

Upload files:

< 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 there is no need to validate the data when submitting the form. They are both boolean attributes. formnovalidate can be applied to inputs of type submit or image. The novalidate attribute can only be set to the form element.

An example of the use of the formnovalidate attribute can be seen on a "save draft" button, where the form has fields required to submit a draft, but not required to save a draft. novalidate will be used in cases where you do not need to validate the form, but want to achieve the benefits of a more convenient user interface offered by new data entry types.

The use of formnovalidate can be seen in the following example:

Email:

< form action = "process.php" >

< label for = "email" >Email:< / label >

< input type = "text" name = "email" value = "[email protected]" >

< input type = "submit" formnovalidate value = "Submit" >

< / form >

And this example shows the use of novalidate:

Email:

< form action = "process.php" novalidate >

To see a description and example of using the global attribute you are interested in, click on it or scroll down the page to its description.

accesskey

The accesskey attribute is used by browsers as a guide to create a keyboard shortcut that activates an element or gives it focus.

Note: Before HTML5, the accesskey attribute could only be used with the following tags: , , , , And . From the fifth HTML versions This attribute can be used with any valid HTML tag.

The value of the accesskey attribute must be a character that can be entered by pressing a single key. Whitespace characters are not allowed as attribute values.

The keyboard shortcuts for the accesskey attribute depend on the browser you are using:

Using the accesskey attribute on different elements with the same value causes the attribute to be ignored.

class

The class attribute is used to later access elements (via the class name) in CSS and JavaScript.

In the class attribute, you can specify not one, but several classes as a value; in this case, the class names must be separated by spaces; the order of the class names does not matter:

If ad blocks of different classes use the same CSS properties With different meanings, then the value that is defined below the others in the CSS code will be applied to the property. Therefore, the order of the class names in the attribute value does not matter, since in this case the cascading mechanism is triggered.

contenteditable

The contenteditable attribute specifies whether the content of this element can be edited by the user. The attribute can take one of the following values:

  • true or empty string ("") - the contents of the element can be edited
  • false - content editing is prohibited
Just some draggable text

The draggable attribute determines whether the user can drag an element from using drag-and-drop API. The attribute can take one of three values:

  • true - indicates that the element can be dragged
  • false - indicates that the element is not dragged
  • auto - specifies that dragging of an element will depend on the default value set in the browser.

Using the id attribute, you can create links to a specific element, and not just to the page as a whole. Such links can lead either to a section of this page or to a section of another page. To create a link to an element, you need to add an id attribute to the sky. The link itself, in this case, will have to contain the name of the identifier of the element to which it refers, which must be preceded by the # symbol. If the link leads to a section current page, then only the identifier name can be specified as the address; if the link leads to a section of another page, then the identifier name is indicated at the very end of the address:

lang

The lang attribute allows you to specify what language is used for the text inside the element. Language codes are used as the attribute value:

Text in English: "Hello world!"

Using this attribute helps browsers correctly display some national characters, speech programs determine the language of the text, and check the text for spelling and grammar checking programs.

The lang attribute can also be used to improve quality in search results search results that are based on the user's linguistic preferences.

spellcheck

The spellcheck attribute specifies whether the element's contents can be checked for spelling errors. The attribute can take one of the following values:

  • true - indicates that the content of the element should be checked for spelling errors if possible.
  • false - indicates that the element should not be checked for spelling errors.

The spellcheck attribute is an enumerable attribute. This means that an explicit attribute value is required. Adding an attribute without a value is prohibited:

The spellcheck attribute specifies only a browser recommendation: browsers should not be able to check for spelling errors. Typically, non-editable elements are not checked for errors, even if the attribute is set to true and the browser supports checking.

style

The style attribute is used to add CSS styles to the element. Styles added using the style attribute take precedence over styles located in the element or in an external file.

When adding styles to an attribute value, the selector and curly braces are not used. Each declaration must end with a semicolon, after which the next declaration can be written. Between properties and their values, as well as between declarations, spaces are optional:

Bold red text

tabindex

The tabindex attribute specifies whether an element can have focus and the order of priority when moving focus between elements (using the "tab" key). The attribute takes an integer as its value:

The number 5 means that the element will receive focus after the element with tabindex="4" and before the element with tabindex="6" . But it is not necessary to give sequential values; in any case, elements with a lower value will receive focus before elements with a higher value. If several elements have the same positive values, then the order in which focus will be received will depend on the order in which they appear in source code document.

title

title attribute used to indicate additional information about the contents of the element (displayed by browsers as a pop-up text tip when hovering the mouse over the element).

The title attribute is often used with images to add a description of the image:

Note: appearance and tooltip size, font and text color are browser dependent and cannot be changed using CSS styles.