Какой тег используют для разметки форм
Перейти к содержимому

Какой тег используют для разметки форм

  • автор:

A step-by-step guide to getting started with HTML forms

Abhishek Jakhar

HTML forms are required when you want to collect some data from the person who visits your website. For example, when you register/login for applications like Uber, Netflix, or Facebook, you enter information like Name, Email, and Password through HTML forms.

Now we will learn all the required elements for creating a form.

NOTE: I have already added the Styling using CSS and so my elements will look different, but they will work in exactly the same way.
If you want to make your elements look like mine then, you can find my CSS file in the links given below:
Custom CSS: https://gist.github.com/abhishekjakhar/493d920a219ed9d88f1846cd31de7751
Normalize CSS:
https://gist.github.com/abhishekjakhar/3a6c25fa61a293b6a56d28f98497808b

Form Element

This is the first element which we will learn. This element wraps all the other elements that go inside of our form. This is the form element.

Our form won’t submit the data anywhere because it is not connected to a server. To connect our form to a server and process our data, we can use any server-side language like Node, Python, Ruby, or PHP. The part of processing the data involves two important attributes that are attached to the form element. Let’s take a look at those attributes.

Attributes:

  1. action: The action attribute is the web address (URL) of a program that processes the information submitted by our form.
  2. method: It is the HTTP method that the browser uses to submit the form, the possible values are POST and GET.
  • POST — Data from the body of the form is sent to the server.
  • GET — Data is sent inside of the URL and parameters are separated with a question mark.

Note: You cannot have forms nested inside another form. That means you cannot have a <form> element inside another<form> element.

Input Element

The input element is the most commonly used form element. It is used to make a text field where the user can type some information for example email, password etc.

Let’s make a text field where the user can type in their name.

Note: The input element is a self-closing tag, so there’s no need to type a closing tag to match the opening tag.

I have added three attributes in the above input tag. Let’s take a look at each one in detail.

type

The type attribute indicates what kind of input we want. If we give a value of text to the type attribute, than what we mean here is that the value which we are entering into the input field is of type text. There are many possible values for this particular attribute. Some possible values are email, tel for telephone and password etc.

Example: When you login into any of your accounts (Amazon/Netflix), you need to enter two things: email and password. So in this particular case the input element is used. The type attribute is given with the value of email and password respectively.

id

The ID attribute is not mandatory, but it’s a good idea to add one. In some cases, this is helpful for targeting elements with CSS/JavaScript. The ID attribute is added so that we can associate labels to specific form controls.

name

The name attribute is necessary. When a form is submitted to the server side code, the server can understand the form data and process the values appropriately.

placeholder

It is a short hint which is displayed in the input field before the user enters a value. As the user starts typing in the input field the placeholder disappears.

Let’s see what a few other basic input elements look like.

Note: Using different values for the type attribute will produce different results. For example you can make input be of type email, text, or password etc. All of them show slightly different behaviour, which you will see below.

HTML forms basics

This article covers the basics of creating standards compliant, best practice HTML forms.

Introduction

Everyone has seen a form. Everyone has used one. But have you coded one?

Most areas where you can input information into web pages are created using HTML forms: entering text or numbers into a text box, ticking a check box, choosing a radio button, or selecting an option from a list. The form is then usually submitted to the website and the data is used in some way. Your customer details might be stored in a database for later use, or the website might be updated after you choose a product to view.

While it is easy to create a functional form, attractive and usable forms take a bit of work. In this article we’ll cover how to create elegant, accessible form structures with HTML, starting with the real basics and working up to some more complex features. We’ll then look at the new form capabilities of in HTML5 in the next article, HTML5 form features.

Step one: The basic code

Let’s start by building a comment form, the sort of form you would use on a website to allow people to give you feedback on something, such as an article you wrote or a product you sell. We’ll start it off very simply:

If you enter this into an HTML document and then open that document in a browser, the code is rendered something like this:

the first form example

Figure 1: The basic form example.

Try it for yourself — enter the above code into your own sample HTML document and load it in a browser. As you examine the code, you’ll see an opening <form> tag, a closing </form> tag, and some bits in between. The form contains three input elements into which you can enter information: two single line text inputs, and a multiline text input. Let’s look at each part.

The <form> element

The <form> element is required to wrap around the form’s content — without it you don’t have a web form. The <form> tag can have a few attributes, which we’ll cover below. Note that you can’t nest a form inside another form.

The <input> element

The <input> element defines an area where you can type or paste information.

The type attribute

There are different type s of <input> elements. We’ll look at them later, but in this case we are using <input type="text"> to specify that we want single line text input fields (the type attribute is mandatory). We have also put “Name:” and “Email:” text next to them, to give visitors an indication of what data we’d like them to enter there.

The name attribute

Every <input> element must also have a name attribute that you, the developer, specify. The only exceptions to this rule are special cases where the value attribute is set to the same value as the type attribute, e.g., type="submit" or type="reset" . The name attribute is needed for the database or other data destination to uniquely identify that piece of data.

When the form is submitted, most scripts use the name attribute to place the form data into a database or into an email that can be read by a person. Thus, if the <input> element is for the visitor’s name, the name attribute would be name="name" or name="first-name" , etc.

Also note that the <input> elements have id attributes whose values match those of the name attributes. This is standard practice, and helps ready the form for processing by JavaScript functions. More about this later.

The value attribute

Every <input> element should also have a value attribute. The value of this attribute depends on the element it is used on:

  • In the case where the field contents are generic, the value attribute can be set to blank — value="" . This tells the processing script to just use whatever the visitor types into the box. If you do enter a value into the value attribute, it will appear in the text input as an initial value that the user can then overwrite.
  • In the case of more complex input with a choice of options such as a checkbox or radio button, you can set the initial value to one of the choices. For example, you can set value="yes" to have the initial choice of a yes/no radio button pair set to yes.
  • In cases where there is only one value so the user doesn’t enter anything, such as submit or hidden, you set the value to equal the final input. For example, you would use value="submit" for a submit button.

Let’s walk through a more complete example of how the value attribute is used:

  • To start, consider a blank (“”) value attribute, where the user enters generic text.
    • The code says: <input type="text" name="first-name" value="" />
    • The user inputs: Jennifer
    • The value of first-name is sent as Jennifer when the form is submitted.
    • The code says: <input type="checkbox" name="mailing-list" value="no" />
    • The user checks the box, as they wish to join the website’s mailing list.
    • The value of mailing-list is sent as “yes” when the form is submitted.

    the <textarea> element

    After the two <input> elements comes something a bit different — the <textarea> element. This element provides a multiple line text input area, and you can even define how many lines are available. Note the cols and rows attributes — these are required for every textarea element, and specify how many columns (lines) tall and how many rows (characters) wide to make the text area.

    <input type="submit">

    Last but not least, there is a special <input> element with the attribute value="submit" . Instead of rendering a text box for input, the submit input will render a button that, when clicked, submits the form’s data to whatever target the form has specified. We’ll learn more about this later in the article.

    Step two: Adding structure and behaviour

    When you run that example, fill in the form, and click Submit, it doesn’t do anything! Why not? And why does it look so bad, all mashed up on one line? The answer is that we haven’t structured it yet, or defined a place for the collected data to be submitted.

    Let’s go back to the drawing board, with a new and improved form:

    This form looks like this when rendered in a browser:

    the second form example

    Figure 2: The second form example — looking better.

    You can also put this example code into an HTML page and play with it, but if you try to submit the form you will get a 404 error — this is because the script.php file the action attribute points to does not actually exist; it is just there to give you the idea of what happens upon form submission. See the section covering the action attribute below for more information.

    Here we have made a few additions to the basic, simple form. Let’s break it down:

    Giving the form an id

    We added an id attribute to provide a unique identifier for the form ( contact-form ) so that it can be more easily styled using CSS or manipulated using JavaScript. All id s must be unique within a page.

    The method attribute: telling the data how to travel

    Lights, camera, action! When you pressed the submit button in the first form and it did nothing, that was because it had no action or method. The method attribute specifies how the data is sent to the script that will process it. The two most common methods are “GET” and "POST".

    • The “GET” method sends the data in the page’s URL. In your browser’s address bar you will sometimes see URLs like http://www.example.com/page.php?data1=value1&data2=value2. ; these are bits of data being transported using the “GET” method. Unless you have a specific reason to use "GET", it is probably best to avoid it if you are trying to send secure information, because anyone can see the information as it is transmitted via the URL.
    • The “POST” method sends the data, via the script that powers the form, either to an email that is sent to the site’s administrator or to a database to be stored and accessed later. “POST” is the more secure and usually the better option; see this W3C article for more information.

    If you are concerned about the security of the data in the form, for example if you are submitting a credit card number to a shopping site, then you should use https with a secure socket layer (SSL). Basically, this means that data will be sent over the secure https protocol instead of the insecure http protocol. Have a look at the URLs next time you are paying for something on a shopping site, or using online banking — you’ll probably see https:// in your address bar, not http:// . Although an https connection is a bit slower to transmit than http, the data is encrypted, so anyone hacking into the data connection can’t make hijack it while it is in transit. Talk to your web host for information on how they can provide you with https and SSL to use with your forms.

    The action attribute: telling the data where to go

    The action attribute specifies what script the form data should be sent to for processing. Many web hosts have a generic send mail script or other form scripts available for use (see your host’s documentation for information) that they have customized to their servers. On the other hand, you could use a server-side script that you or someone else has created to power your form. Most of the time, web developers use languages such as PHP, Perl, or Ruby to create a script that will process the form — you could, for example, send an email containing the form information, or input the form information into a database to be stored for later use. It is outside of the scope of this article to teach you how to write server-side code — please inquire with your host to find out what they offer, or find a nice programmer to befriend.

    Hidden form inputs

    The second line that’s been added to our Step Two form is the “hidden” input field — this is a redirect. Under the goal of separating markup structure from presentation and behaviour, it is ideal to use the script that will power the form to also redirect the user when the form is submitted. You don’t want your users to be left sitting there looking at the form page, wondering what to do next after they’ve submitted the form; we’re sure you’ll agree that it is a much better user experience to instead redirect your users after a successful form submission to a thank you page featuring “what to do next” links. This example specifies that after the form is submitted, the user will be redirected to the Opera homepage.

    Structuring with an unordered list

    To improve the look of the form, we have put all the form elements into an unordered list so that we can use CSS to hook into the HTML structure and make the form look better, by lining it up and giving it some polish. Some developers would argue against using an unordered list to mark up a form, and would suggest using a set of <div> elements instead. To be perfectly honest, either way is fine, so pick the one that suits you best. Whatever layout method you use, be sure to style it appropriately with CSS so it doesn’t look awkward and clunky.

    https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

    Labels for accessibility

    Last but not least in Step Two, we’ve labeled the form elements. It is best to give all the form elements corresponding <label> elements. These labels are tied to their respective form elements by giving the <input> and <textarea> elements id s that have the same value as the labels’ for attributes, or by nesting the input control inside the label element itself. This is great because it not only gives a visual indicator of the purpose of each form field on the screen, but it also gives the form fields more meaning semantically. In addition, a visually impaired person using the page with a screen reader can now tell which label goes with which form element and have more of a clue what data to fill into what input. The id s can also be used for targeting individual form fields with CSS styles.

    By now you may be wondering why id attributes are included as identifiers in form elements as well as name attributes. The answer is that <input> elements without name attributes are not submitted to the server, so those are definitely needed. The id attributes are needed to associate form elements with their corresponding <label> elements. You should therefore use both.

    The second form looks a bit better, but isn’t quite ready for publishing. Time to improve the structure further!

    Step three: Adding some more complex form elements

    The next version of the form code is:

    When rendered in a browser, that form looks like this:

    the third form example

    Figure 3: Some new, more complex form elements!

    What have we added here? Let’s have a look.

    Checkboxes: providing multiple yes/no choices

    The first thing we added is a set of checkboxes:

    There is nothing special about these; each element creates a checkbox that can be checked on and off by the site visitor. They are identified by IDs, and their data is identified by their name attributes. When the form is submitted, any data items not checked are submitted as “off” or "no".

    Radio buttons: a multiple choice option

    Next, we have a set of radio buttons:

    The only thing here that is different from the checkboxes (apart from the type attribute value of course) is the name values — notice that they are all the same. This is because whereas with checkboxes you are dealing with separate items of data with on/off values, while with sets of radio buttons you are dealing with a single item of data that cane take one of several values. Having the name attributes all set to the same value makes these radio buttons part of the same set, and you can only select one of them at once.

    The checked attribute

    Note the checked attribute on the above two bits of code, which makes the element selected by default when the page loads.

    Uploading a file

    This line of code creates a file uploader, used for uploading photos or other objects to be submitted with the form. Clicking the input field activates your operating system’s “File” or “Open” dialog and allows you to choose a file to be uploaded when the form is submitted.

    Select and option: creating a multi-line dropdown menu

    The last new bit of code looks like this:

    The <select> element is quite different from the others we’ve seen so far: it creates a single line form control that, when activated, drops down to reveal multiple options, as defined in the <option> elements. The value attribute contains the actual data that is submitted for the selected option when you submit the form, and the text content inside the elements are the values the user sees.

    Step four: further structuring with fieldsets and legends

    The final form example is identical to the last one, except that we have wrapped the different major parts of the form in <fieldset> elements, and given each one its own <legend> element. For example:

    When rendered in a browser, these look like this:

    the fourth and final form example

    Figure 4: More structuring with fieldset and legend.

    Explaining fieldset and legend

    <fieldset> and <legend> are not mandatory, but they are very useful for more complex forms and for presentation.

    The <fieldset> element allows you to organize the form into semantic modules. In a more complex form, you could use different <fieldset> s to contain address information, billing information, customer preference information, and so on. The <legend> element allows you to add a label to each <fieldset> section.

    A little bit of style…

    We’ve also applied a bit of CSS to this form, to style the structural markup. This is applied to the third form example using an external stylesheet. The two most important tasks we want the CSS to do are to add margins to line up the labels and input boxes, and to get rid of the unordered list’s bullets. Here is the CSS that resides in the external stylesheet:

    What does it do? The first line styles the fieldset border to not take up the whole page; you could also omit the border completely using . The second line puts a margin of 10 pixels on the <li> elements to put a little visual room between each list item, and gets rid of the bullets. The third and fourth lines set a left margin on the <input> and <textarea> elements so that they don’t crowd the labels and line up better.

    You can see that this little bit of CSS makes our form look better, but you could improve it even more. For more information on styling forms, see Nick Rigby’s article, Prettier Accessible Forms.

    Conclusion

    This article examined the most basic elements and features of HTML forms. Everything examined here is available in HTML4; for a discussion of the new form features available in HTML5, see the next article, HTML5 form features.

    Какой тег используют для разметки форм

    Формы разные нужны, формы разные важны. Без этого тега ни одна форма работать не будет!

    Время чтения: 6 мин

    1. Кратко
    2. Пример
    3. Как понять
    4. Как пишется
    5. Атрибуты
    6. Подсказки
    7. Ещё примеры
    8. На практике
      1. Николай Лопин советует
      2. Алёна Батицкая советует
      • Алёна Батицкая ,
      • Светлана Коробцева

      Обновлено 17 мая 2022

      Кратко

      Скопировать ссылку «Кратко» Скопировано

      Тег <form> добавляет на страницу форму, которую пользователь может заполнить. Например, ввести своё имя, фамилию или почту. Данные формы отправляются на сервер.

      Пример

      Скопировать ссылку «Пример» Скопировано

      Как понять

      Скопировать ссылку «Как понять» Скопировано

      Сайты используют формы, чтобы получить какую-то информацию от пользователя. Это может быть форма заказа в онлайн-магазине или форма обратной связи. Пользователь заполняет поля или выбирает нужную опцию в списке, а после отправки формы эти данные можно обработать.

      Как пишется

      Скопировать ссылку «Как пишется» Скопировано

      Стилизовать <form> можно с помощью CSS.

      На странице можно сделать сколько угодно форм. Но одновременно пользователь сможет отправить только одну заполненную форму.

      Атрибуты

      Скопировать ссылку «Атрибуты» Скопировано

      action — здесь указывается ссылка на скрипт, который обработает форму. Это может быть полная URL-ссылка, а может быть относительная, типа html / sendform . Если не указать атрибут action , то страница будет просто обновляться каждый раз, когда отправляется форма.

      method — определяет, каким способом будут отправлены на сервер данные, которые ввёл пользователь. Есть два варианта:

      • get — ответы пользователя дописываются в URL в формате «параметр=значение», например «email=name@yandex.ru». Выглядит это так: site . com / form ? name = Max&email = name@yandex . ru . То есть параметр — это то, что вы спрашиваете у пользователя, а значение — его ответ. Пары «параметр=значение» разделяются знаком & . Вариант method = «get» используется по умолчанию, но у него есть ограничение: URL не должен получиться длиннее, чем 3000 символов.
      • post — данные из формы пакуются в тело формы и отправляются на сервер. В этом случае нет ограничений по объёму данных, поэтому этот способ подойдёт для заполнения базы данных или отправки файлов.

      name — уникальное имя формы. Пользователь его не увидит, зато скрипты смогут найти нужную форму. Например, по этому имени, можно получить доступ к форме из коллекции document . forms .

      autocomplete — включает или выключает автозаполнение для формы. Браузер может подставить данные, которые пользователь сохранил ранее, например, пароль, номер банковской карты или адрес. Если у пользователя в настройках браузера отключена функция автозаполнения, то этот атрибут уже ни на что не повлияет. Атрибут autocomplete можно задать и для конкретных элементов. Есть два значения:

      • on — значение по умолчанию. Включает автозаполнение для этой формы.
      • off — выключает автозаполнение. Например, если форма собирает уникальные данные типа капчи («Введите слово с картинки»).

      novalidate — у этого атрибута нет значения. Если его добавить, браузер не будет проверять правильность заполнения формы. Например, верно ли введён адрес почты или URL для тегов <input type = «email»> и <input type = «url»> соответственно. Обычно браузер проверяет, не пропустили ли вы @ или домен. В том числе, проверяется и заполнение обязательных полей.

      enctype — определяет, какой вид кодирования будет применён к данным из формы. Этот атрибут обязательно надо ставить, если через форму отправляются файлы, в остальных случаях — не обязательно. Есть три варианта кодирования:

      • application / x — www — form — urlencoded — это значение по умолчанию. Данные будут кодироваться так, что пробелы превратятся в знак + , а символы вроде кириллицы будут представлены в шестнадцатеричном значении. Например, так будет выглядеть имя Степан: % D0 % A1 % D1 % 82 % D0 % B5 % D0 % B F % D0 % B0 % D0 % B D ��
      • multipart / form — data — вариант, который надо указать, если через форму отправляются файлы. В этом случае данные не кодируются.
      • text / plain — в этом случае пробелы меняются на + , а остальные символы передаются без изменений.

      accept — charset — задаёт кодировку, в которой сервер принимает данные из формы. Самая распространённая кодировка — UTF — 8 . Можно указать один вариант или несколько. Например, accept — charset = » U T F — 8 Windows — 1251″ . В этом случае названия кодировок нужно разделять пробелами. Здесь можно задать значение по умолчанию: accept — charset = » U N K N O W N» . Тогда кодировка будет такой, какая используется на странице с формой.

      Подсказки

      Скопировать ссылку «Подсказки» Скопировано

      �� Никогда не используйте method = «get» , если хочется отправить конфиденциальные данные, потому что их можно будет легко прочитать в запросе, который отправляет форма, и даже в адресной строке браузера.

      �� Вариант method = «get» удобен тем, что полученный URL с ответами можно сохранить в закладки. Например, пользователь может заполнить форму и поделиться ссылкой с результатами с кем-нибудь ещё.

      Ещё примеры

      Скопировать ссылку «Ещё примеры» Скопировано

      Вот простая форма:

      Попробуем отправить данные, которые введёт пользователь, на почту. Для этого вместо URL-ссылки мы пропишем action = «mailto : html@yandex . ru» . Ключевое слово mailto : позволяет отправить что угодно на электронную почту. Не забудьте добавить атрибут enctype = «text / plain» тегу <form> , чтобы письмо отображалось корректно:

      На практике

      Скопировать ссылку «На практике» Скопировано

      Николай Лопин советует

      Скопировать ссылку «Николай Лопин советует» Скопировано

      �� Без тега <form> форма не будет работать, но это не всё, что нужно для получения данных. Введённые пользователем данные нужно собирать и отправлять на сервер. Уже на сервере с данными что-то будет происходить: будет отправляться письмо на почту или формировать заказ. За обработку и отправку данных отвечают атрибуты method и action .

      Если у тега формы не указывать ни action , ни method , как в примере ниже, то данные никуда не отправятся, а страница перезагрузится:

      Отправка формы с помощью атрибутов action и method происходит синхронно — браузер отправляет запрос по адресу и рисует на экран все, что вернётся в ответ. Это приводит к полной перезагрузке страницы.

      Можно отправлять формы асинхронно, без перезагрузки страницы, но для этого нужно писать JavaScript код, который будет отправлять запрос, получать ответ и обновлять страницу данными из ответа. Читайте, как делать асинхронные формы в статье «Работа с формами» раздела JavaScript.

      Алёна Батицкая советует

      Скопировать ссылку «Алёна Батицкая советует» Скопировано

      �� Формы очень часто встречаются на сайтах. С их помощью пользователю предлагается оформить подписку, отправить запрос на цену, записаться на приём к врачу, авторизоваться на сайте и тому подобное.

      Посвятите время детальному изучению форм. В том числе тому, как их стилизовать. Это отдельная боль — стилизовать разные поля формы крайне муторно. А чтобы делать это кроссплатформенно, нужно изрядно набить руку.

      Как структурировать HTML-формы

      Получив базовые знания, теперь мы более подробно рассмотрим элементы, используемые для придания структуры и значения различным частям форм.

      Уровень подготовки: Основы компьютерной грамотности, и базовые знания HTML.
      Цель: Разобраться как структурировать HTML формы и задавать им семантику для того, чтобы они были удобны и доступны в использовании.

      Гибкость HTML форм делает их одной из самых сложных структур в HTML; вы можете создать любую форму, используя элементы и атрибуты форм. Использование правильной структуры, при создании HTML форм, поможет гарантировать их удобство и доступность.

      Элемент <form>

      Элемент <form> формально определяет форму и атрибуты, которые определяют поведение этой формы. Каждый раз, когда вы хотите создать HTML-форму, вам нужно начать с создания элемента <form> , поместив внутрь него всё содержимое. Многие вспомогательные технологии или браузерные плагины могут обнаруживать элементы <form> и реализовывать специальные хуки, чтобы их было проще использовать.

      Мы уже встречались с этим в предыдущей статье.

      Предупреждение: Внимание: Строго запрещается размещать форму внутри другой формы. Такое размещение может привести к непредсказуемому поведению форм, в зависимости от браузера.

      Стоит учесть, что всегда можно использовать элементы формы вне <form> . Тогда по умолчанию этот элемент формы не имеет ничего общего со всеми формами. Вы можете связать его с формой с помощью атрибута form . В HTML5 был представлен атрибут form для элементов HTML форм, который позволяет явно связать элемент с формой, даже если он не заключён внутри <form> .

      Элементы <fieldset> и <legend>

      Элемент <fieldset> — это удобный способ стилистической и семантической группировки элементов формы. Вы можете установить заголовок <fieldset> , добавив элемент <legend> сразу после открывающего тега <fieldset> . Текст элемента <legend> формально описывает назначение содержимого <fieldset> .

      Различные вспомогательные технологии будут использовать <legend> как часть метки label всех элементов внутри <fieldset> . Например, такие экранные дикторы как Jaws или NVDA произносят заголовок формы <legend> перед произношением названия меток элементов.

      Примечание: вы можете найти этот пример в fieldset-legend.html (также посмотрите на результат).

      Читая эту форму, экранный диктор произнесёт «Fruit juice size small» для первого элемента, «Fruit juice size medium» — для второго, «Fruit juice size large» — для третьего.

      Вариант использования в этом примере является одним из наиболее важных. Каждый раз, когда у вас есть набор переключателей, вам нужно поместить их внутри <fieldset> . Также <fieldset> можно использовать для разделения формы. В идеале, длинную форму разделяют на несколько страниц, однако, если она должна находиться на одной странице, распределение связанных элементов в разные <fieldset> может повысить удобство использования.

      Из-за своего влияния на вспомогательные технологии элемент <fieldset> является одним из ключевых элементов для построения доступных форм; однако вы не должны им злоупотреблять. Если возможно, старайтесь проверять, как экранный диктор интерпретирует вашу форму.

      Элемент <label>

      В предыдущей статье мы увидели, что элемент <label> принято использовать для указания текстов-подсказок (лейблов) в HTML-формах. Это самый важный элемент для построения доступных форм — при правильной реализации скринридеры будут озвучивать текст-подсказку вместе со связанными элементами. Посмотрите на этот пример из предыдущей статьи:

      При правильно связанном элементе <label> с элементом <input> через атрибуты for и id соответственно (атрибут for ссылается на атрибут id соответствующего виджета формы), скринридер прочтёт вслух что-то наподобие «Name, edit text».

      Если <label> не правильно установлен, скринридер прочитает это как «Edit text blank», что не несёт в себе никакой уточняющей информации, позволяющей понять предназначение данного текстового поля.

      Обратите внимание на то, что виджет формы может быть вложен в элемент <label> , как на примере:

      Однако даже в таких случаях лучше всё равно указывать атрибут for , так как некоторые вспомогательные технологии не распознают неявную связь между текстами-подсказками и виджетами.

      Лейблы тоже кликабельны!

      Ещё одно преимущество при правильно установленных текстах-подсказках заключается в том, что по ним можно кликнуть для активации связанных с ними виджетов. Это поддерживается во всех браузерах. Это удобно как для текстовых полей ввода, в которых устанавливается фокус при клике на текст-подсказку, так и для радио-кнопок и чекбоксов — область попадания такого элемента управления может быть очень маленькой, поэтому полезно сделать её как можно больше.

      Примечание: вы можете посмотреть этот пример тут checkbox-label.html (также можно посмотреть код вживую).

      Несколько лейблов

      На самом деле вы можете добавить несколько текстов-подсказок на один виджет формы, но это не очень хорошая идея, так как у некоторых вспомогательных технологий могут возникнуть проблемы с обработкой такой структуры. Вместо использования нескольких лейблов, лучше вложить виджет формы внутрь одного элемента <label> .

      Рассмотрим этот пример:

      Параграф на первой строке примера описывает правило для обязательных элементов. Вначале необходимо убедиться, что вспомогательные технологии, такие как программы чтения с экрана, отображают или озвучивают их пользователю, прежде чем он найдёт требуемый элемент. Таким образом они будут знать, что означает звёздочка. Программа чтения с экрана будет произносить звёздочку как «звёздочку» или «обязательно», в зависимости от настроек программы чтения с экрана — в любом случае, первый абзац даёт понимание того, что будет означать звёздочка далее в форме.

      • В первом примере лейбл не будет прочитан вместе с текстовым полем — получится лишь «edit text blank» и отдельно читаемые тексты-подсказки. Множественные элементы <label> могут быть неправильно интерпретированы программой чтения с экрана.
      • Второй пример немного лучше — лейбл будет прочитан вместе с текстовым полем и будет звучать как «name star name edit text», однако тексты-подсказки всё ещё разделены. Это всё ещё немного сбивает с толку, но на этот раз ситуация немного лучше, потому что с текстовое поле связано с текстом-подсказкой.
      • Третий пример — лучший, так как весь лейбл будет связан с текстовым полем и озвучен целиком, а при чтении текст будет звучать как «name star edit text».

      Примечание: В зависимости от программы для чтения с экрана результаты могут немного отличаться. В данной статье для тестирования использовался VoiceOver (NVDA ведёт себя аналогично). Также мы были бы рады, если бы вы поделились своим опытом.

      Примечание: вы можете найти этот пример на GitHub required-labels.html (также можно посмотреть вживую). Запускайте пример, закомментировав остальные, иначе скриридеры не смогут правильно распознать контент, если у вас будет несколько лейблов и несколько текстовых полей с одинаковым ID!

      Часто используемые с формами HTML-структуры

      Помимо структур, характерных только для HTML-форм, хорошо помнить, что формы — это просто HTML. Это означает, что вы можете использовать всю мощь HTML для структурирования HTML-формы.

      Как вы можете заметить в примерах, оборачивать лейбл и виджет формы в элемент <div> — это общепринятая практика. Элемент <p> также часто используется, как и HTML-списки (последние часто используются для структурирования множественных чекбоксом или радио-кнопок).

      В добавок к элементу <fieldset> часто используют HTML-заголовки (например, <h1> (en-US), <h2> (en-US)) и секционирование (например, <section> ) для структурирования сложных форм.

      Прежде всего, вам нужно найти стиль, который будет удобен именно вам для программирования и который также позволит создавать доступные и удобные формы.

      Каждый отдельный раздел функциональности содержится в элементах <section> и <fieldset> , содержащий переключатели. Каждый отдельный раздел функциональности должен находиться в отдельном элементе <section> с элементами <fieldset> , содержащими переключатели.

      Активное обучение: построение структуры формы

      Давайте применим эти идеи на практике и построим более сложноструктурируемую форму — формы оплаты. Форма будет содержать некоторые типы виджетов формы, которые вы можете пока не понять — не переживайте об этом, вы найдёте информацию в следующей статье (Основные нативные элементы управления формами (en-US) ). А пока внимательно прочитайте описание, следуя приведённым ниже инструкциям, и начинайте формировать представление о том, какие элементы обёртки мы используем для структурирования формы и почему.

      1. Для начала сделайте локальную копию пустого шаблона и CSS для нашей платёжной формы в новой директории на вашем компьютере.
      2. Сначала подключите CSS к HTML, добавив следующую строку кода внутрь HTML-элемента <head> :

      Вы можете увидеть законченную форму в действии ниже (также её можно найти на GitHub — посмотрите payment-form.html и живой пример):

      Протестируйте себя!

      Вы дошли до конца статьи, но можете ли вспомнить самую важную информацию? Далее вы можете найти тест, который поможет убедиться, что вы усвоили знания прежде чем двигаться дальше — посмотрите Test your skills: Form structure (en-US) .

      Заключение

      Теперь у вас есть все необходимые знания для того, чтобы правильно структурировать вашу HTML-форму. Мы подробнее раскроем затронутые здесь темы в нескольких последующих статьях. В следующей же статье мы изучим все возможные типы виджетов форм, которые могут понадобиться для сбора информации от ваших пользователей.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *