Формы

Html5 input types and attributes

Элементы формы

Рассмотрим элементы управления, используемые в формах.

К их значению можно получить доступ через свойство (строка) или (булево значение) для чекбоксов.

Вот так:

Используйте вместо

Обратим внимание: хоть элемент и хранит своё значение как вложенный HTML, нам не следует использовать для доступа к нему. Там хранится только тот HTML, который был изначально на странице, а не текущее значение

Там хранится только тот HTML, который был изначально на странице, а не текущее значение.

Элемент имеет 3 важных свойства:

  1. – коллекция из подэлементов ,
  2. – значение выбранного в данный момент ,
  3. – номер выбранного .

Они дают три разных способа установить значение в :

  1. Найти соответствующий элемент и установить в значение .
  2. Установить в значение нужного .
  3. Установить в номер нужного .

Первый способ наиболее понятный, но и являются более удобными при работе.

Вот эти способы на примере:

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

Их коллекцию можно получить как , например:

Полное описание элемента доступно в спецификации .

Элемент редко используется сам по себе, но и здесь есть кое-что интересное.

В есть красивый короткий синтаксис для создания элемента :

Параметры:

  • – текст внутри ,
  • – значение,
  • – если , то ставится HTML-атрибут ,
  • – если , то элемент будет выбранным.

Тут может быть небольшая путаница с и

Всё просто: задаёт HTML-атрибут, его можно получить как , а – выбрано значение или нет, именно его важно поставить правильно. Впрочем, обычно ставят оба этих значения в или не ставят вовсе (т.е

).

Пример:

Тот же элемент, но выбранный:

Элементы имеют свойства:

Выбрана ли опция.
Номер опции среди других в списке .
Значение опции.
Содержимое опции (то, что видит посетитель).

Examples

email input

<label for="emails">Who do you want to email?</label>
<input type="email" multiple name="emails" id="emails" list="drawfemails" required size="64">

<datalist id="drawfemails">
  <option value="">Grumpy</option>
  <option value="">Happy</option>
  <option value="">Sleepy</option>
  <option value="">Bashful</option>
  <option value="">Sneezy</option>
  <option value="">Dopey</option>
  <option value="">Doc</option>
</datalist>

file input

When is set on the file input type, the user can select one or more files:

<form method="post" enctype="multipart/form-data">
  <p>
    <label for="uploads">
       Choose the images you want to upload:
    </label>
    <input type="file" id="uploads" name="uploads" accept=".jpg, .jpeg, .png, .svg, .gif" multiple>
  </p>
  <p>
    <label for="text">Pick a text file to upload: </label>
    <input type="file" id="text" name="text" accept=".txt">
 </p>
  <p>
    <input type="submit" value="Submit">
  </p>
</form>

Note the difference in appearance between the example with set and the other input without.

When the form is submitted,had we used each selected file’s name would have been added to URL parameters as. However, since we are submitting multipart form data, we much use post. See the element and for more information.

select

The attribute on the element represents a control for selecting zero or more options from the list of options. Otherwise, the element represents a control for selecting a single from the list of options. The control generally has a different appearance based on the presence of the multiple attribute, with most browsers displaying a scrolling list box instead of a single line dropdown when the attribute is present.

<form method="get" action="#">
<p>
 <label for="dwarfs">Select the woodsmen you like:</label>
  <select multiple name="drawfs" id="drawfs">
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
  </select>
</p>
<p>
 <label for="favoriteOnly">Select your favorite:</label>
  <select name="favoriteOnly" id="favoriteOnly">
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
  </select>
</p>
<p>
  <input type="submit" value="Submit">
</p>
</form>

Note the difference in appearance between the two form controls.

There are a few ways to select multiple options in a element with a attribute. Depending on the operating system, mouse users can hold the Ctrl, Command, or Shift keys and then click multiple options to select/deselect them. Keyboard users can select multiple contiguous items by focusing on the element, selecting an item at the top or bottom of the range they want to select using the Up and Down cursor keys to go up and down the options. The selection of non-contiguous is not as well supported: items should be able to be selected and deselected by pressing Space , but support varies between browsers.

Styling the HTML Multiselect: Using CSS Properties

A common practice that many web developers use is the possibility to style the default visual output of the HTML multiselect syntax using specific CSS properties. We are first going to show you the HTML syntax and then, include the CSS styling properties with adequate values.

– Code Example 7

You should create an HTML div element to easily style all the HTML options, as shown here:

<label for=”multi-select”> Multiple Select Syntax </label><div class=”select select-multiple”><select id=”select” multiple><option value=”titanic”> Titanic </option><option value=”premonition”> Premonition </option><option value=”pianist”> Pianist </option><option value=”everything”> All the above </option></select></div>

This is all it takes to create the HTML syntax.

– Code Example 8: Adding Specific CSS Styling Properties

Once your HTML syntax is ready, it is time to add the CSS styling properties. In the following example, we are going to show you how to do it:

select {
appearance: none;
background-color: transparent;
border: none;
padding: 0.2em;
margin: 0;
width: 95%;
font-family: inherit;
font-size: inherit;
line-height: inherit;
z-index: 2;
outline: none;
}
.select {
display: grid;
grid-template-areas: “select”;
align-items: center;
position: relative;
select,
&::after {
grid-area: select;
}
min-width: 21ch;
max-width: 41ch;
border: 2px solid green;
border-radius: 0.36em;
padding: 0.19em 0.4em;
font-size: 1.42rem;
cursor: pointer;
line-height: 1.2;
background: #f1f1f1;
&::after {
justify-self: end;
width: 0.9em;
height: 0.4em;
background-color: green;
}
}

All the properties are shown here and their values are going to completely overhaul the default visual appearance of your HTML multiselect syntax. You can include different properties and values to achieve the desired look. It is really easy, so give it a try.

Навигация: формы и элементы

Формы в документе входят в специальную коллекцию .

Это так называемая «именованная» коллекция: мы можем использовать для получения формы как её имя, так и порядковый номер в документе.

Когда мы уже получили форму, любой элемент доступен в именованной коллекции .

Например:

Может быть несколько элементов с одним и тем же именем, это часто бывает с кнопками-переключателями .

В этом случае является коллекцией, например:

Эти навигационные свойства не зависят от структуры тегов внутри формы. Все элементы управления формы, как бы глубоко они не находились в форме, доступны в коллекции .

как «подформа»

Форма может содержать один или несколько элементов внутри себя. Они также поддерживают свойство , в котором находятся элементы управления внутри них.

Например:

Сокращённая форма записи:

Есть более короткая запись: мы можем получить доступ к элементу через .

Другими словами, вместо мы можем написать .

Это также работает, но есть небольшая проблема: если мы получаем элемент, а затем меняем его свойство , то он всё ещё будет доступен под старым именем (также, как и под новым).

В этом легче разобраться на примере:

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

Code Examples and Syntax: The HTML Select Multiple

The HTML multiselect syntax is easy to create and you only need a single HTML element. All you have to do is to add the HTML multiple attributes inside the opening HTML select tag. This is going to tell your browser that users can select more than one option from the whole list. Consequently, you are supposed to wrap several HTML option elements inside the HTML select tags.

– Code Example 1:

The following example is going to show you how to create the basic HTML multiselect syntax:

<select name=”State” multiple><option value=”Arizona”> Arizona </option><option value=”Texas”> Texas </option><option value=”Indiana”> Indiana </option><option value=”Alaska”> Alaska </option></select>

As you can see, all you are supposed to do is to include the HTML multiple attributes inside the opening HTML select tag. Since this Boolean attribute represents an empty string, you do not have to assign a specific value. This syntax is going to create a select box, rather than a dropdown menu on your web page. Since the HTML select element is the most important part of the whole syntax, let us learn something more about it.

Making an HTML file input accept multiple files

The multiple attribute is typically used on an input type of “file” to allow the user to select multiple files at once. This is the most common application for this attribute.

The syntax will be as follows:

As a result, we will be able to choose multiple files from the file picker.

However, you must also change the name to reflect an array if you want to receive them on the backend.

By doing this, we can make sure that our backend receives them as an array rather than just the first chosen file.

For example, we would get the following in PHP:

Naturally, this will vary depending on the backend language you’re using. At least you know it will come in the form of a value array.

Form & Input Attributes

To accommodate all of the different form, input, and control elements, there are a number of attributes and corresponding values. These attributes and values serve a handful of different functions, such as disabling controls and adding form validation. Described next are some of the more frequently used and helpful attributes.

Disabled

The Boolean attribute turns off an element or control so that it is not available for interaction or input. Elements that are disabled will not send any value to the server for form processing.

Applying the Boolean attribute to a element will disable all of the form controls within the fieldset. If the attribute has a value, the Boolean attribute is ignored.

See the Pen Disabled by Shay Howe (@shayhowe) on CodePen.

Placeholder

Placeholder Demo

See the Pen Placeholder by Shay Howe (@shayhowe) on CodePen.

The main difference between the and attributes is that the attribute value text stays in place when a control has focus unless a user manually deletes it. This is great for pre-populating data, such as personal information, for a user but not for providing suggestions.

Required

The HTML5 Boolean attribute enforces that an element or form control must contain a value upon being submitted to the server. Should an element or form control not have a value, an error message will be displayed requesting that the user complete the required field. Currently, error message styles are controlled by the browser and cannot be styled with CSS. Invalid elements and form controls, on the other hand, can be styled using the and CSS pseudo-classes.

Required Demo

See the Pen Required by Shay Howe (@shayhowe) on CodePen.

Other form and form control attributes include, but are not limited to, the following. Please feel free to research these attributes as necessary.

Description

The element, having the «file» value in its attribute, represents a control to select a list of one or more files to be uploaded to the server. When the form is submitted, the selected files are uploaded to the server, along with their name and type.

For the selected files to be properly uploaded to the server, the value «multipart/form-data» must be present in the ‘s attribute, or in the attribute of the button used to submit the form.

When the boolean attribute is present, users may select more than one file to be uploaded to the server.

The attribute may be used in this element to give a hint to the browser about what types of files the user should be able to submit. With this information, the browser may set restrictions about the files a user can pick or provide extended functionalities for specific types of files, like for example, allowing the capture of a picture with the webcam when the allowed types are of images.

Multiple Choice Inputs & Menus

Apart from text-based input controls, HTML also allows users to select data using multiple choice and drop-down lists. There are a few different options and elements for these form controls, each of which has distinctive benefits.

Radio Buttons

Radio buttons are an easy way to allow users to make a quick choice from a small list of options. Radio buttons permit users to select one option only, as opposed to multiple options.

To create a radio button, the element is used with a attribute value of radio. Each radio button element should have the same attribute value so that all of the buttons within a group correspond to one another.

With text-based inputs, the value of an input is determined by what a user types in; with radio buttons a user is making a multiple choice selection. Thus, we have to define the input value. Using the attribute, we can set a specific value for each element.

Additionally, to preselect a radio button for users we can use the Boolean attribute checked.

Radio Buttons Demo

See the Pen Radio Buttons by Shay Howe (@shayhowe) on CodePen.

Check Boxes

Check boxes are very similar to radio buttons. They use the same attributes and patterns, with the exception of checkbox as their attribute value. The difference between the two is that check boxes allow users to select multiple values and tie them all to one control name, while radio buttons limit users to one value.

Check Boxes Demo

See the Pen Check Boxes by Shay Howe (@shayhowe) on CodePen.

Drop-Down Lists

Drop-down lists are a perfect way to provide users with a long list of options in a practi- cal manner. A long column of radio buttons next to a list of different options is not only visually unappealing, it’s daunting and difficult for users to comprehend, especially those on a mobile device. Drop-down lists, on the other hand, provide the perfect format for a long list of choices.

To create a drop-down list we’ll use the and elements. The element wraps all of the menu options, and each menu option is marked up using the element.

The attribute resides on the element, and the attribute resides on the elements that are nested within the element. The attribute on each element then corresponds to the attribute on the element.

Each element wraps the text (which is visible to users) of an individual option within the list.

Much like the Boolean attribute for radio buttons and check boxes, drop-down menus can use the Boolean attribute to preselect an option for users.

Drop-Down Lists Demo

See the Pen Drop-Down Lists by Shay Howe (@shayhowe) on CodePen.

Multiple Selections

The Boolean attribute , when added to the element for a standard drop-down list, allows a user to choose more than one option from the list at a time. Additionally, using the Boolean attribute on more than one element within the menu will preselect multiple options.

The size of the element can be controlled using CSS and should be adjusted appropriately to allow for multiple selections. It may be worthwhile to inform users that to choose multiple options they will need to hold down the Shift key while clicking to make their selections.

Input text multiple values

However, if you need to allow users to enter multiple values in a text-based input, you can use a delimiter such as a comma or a semicolon to separate the values.

When the form is submitted, you can then split the values based on the delimiter to process them as separate values.

For example, you could use a text input field like this:

If the user enters three values, “apple”, “banana”, and “orange”, separated by commas, the form data will be sent to the server as follows:

In your server-side code, you can then split the string into an array of values using the explode() function in PHP or a similar function in another language.

Here’s an example of how you might process the input in PHP:

Note that this approach is not recommended if you need to validate or enforce data constraints on each individual value. In such cases, it is better to use separate input fields or a different input type that supports multiple values.

Examples

email input

<label for="emails">Who do you want to email?</label>
<input type="email" multiple name="emails" id="emails" list="drawfemails" required size="64">

<datalist id="drawfemails">
  <option value="">Grumpy</option>
  <option value="">Happy</option>
  <option value="">Sleepy</option>
  <option value="">Bashful</option>
  <option value="">Sneezy</option>
  <option value="">Dopey</option>
  <option value="">Doc</option>
</datalist>

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

Некоторые браузеры поддерживают параметров из связанного для последующих адресов электронной почты, когда присутствует . Другие нет.

file input

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

<form method="post" enctype="multipart/form-data">
  <p>
    <label for="uploads">
       Choose the images you want to upload:
    </label>
    <input type="file" id="uploads" name="uploads" accept=".jpg, .jpeg, .png, .svg, .gif" multiple>
  </p>
  <p>
    <label for="text">Pick a text file to upload: </label>
    <input type="file" id="text" name="text" accept=".txt">
 </p>
  <p>
    <input type="submit" value="Submit">
  </p>
</form>

Обратите внимание на разницу во внешнем виде между примером с набором и другим входным без. Когда форма отправлена, если бы мы использовали , имя каждого выбранного файла было бы добавлено к параметрам URL как

Однако, поскольку мы отправляем данные составной формы, мы часто используем post. См. элемент для получения дополнительной информации

Когда форма отправлена, если бы мы использовали , имя каждого выбранного файла было бы добавлено к параметрам URL как . Однако, поскольку мы отправляем данные составной формы, мы часто используем post. См. элемент для получения дополнительной информации.

select

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

<form method="get" action="#">
<p>
 <label for="dwarfs">Select the woodsmen you like:</label>
  <select multiple name="drawfs" id="drawfs">
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
  </select>
</p>
<p>
 <label for="favoriteOnly">Select your favorite:</label>
  <select name="favoriteOnly" id="favoriteOnly">
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
  </select>
</p>
<p>
  <input type="submit" value="Submit">
</p>
</form>

Обратите внимание на разницу во внешнем виде двух элементов управления формой. Есть несколько способов выбрать несколько параметров в элементе с атрибутами

В зависимости от операционной системы пользователи мыши могут удерживатьCtrl,Command, orShiftключи, а затем щелкните несколько параметров, чтобы выбрать / отменить их выбор. Пользователи клавиатуры могут выбрать несколько смежных элементов, сосредоточив внимание на элементе , выбрав элемент вверху или внизу диапазона, который они хотят выбрать, используяUpandDownклавиши курсора для перехода вверх и вниз по опциям.Выбор несмежных поддерживается не так хорошо:элементы должны быть выделены и отменены нажатием клавишSpace, но поддержка зависит от браузера

Есть несколько способов выбрать несколько параметров в элементе с атрибутами. В зависимости от операционной системы пользователи мыши могут удерживатьCtrl,Command, orShiftключи, а затем щелкните несколько параметров, чтобы выбрать / отменить их выбор

Пользователи клавиатуры могут выбрать несколько смежных элементов, сосредоточив внимание на элементе , выбрав элемент вверху или внизу диапазона, который они хотят выбрать, используяUpandDownклавиши курсора для перехода вверх и вниз по опциям.Выбор несмежных поддерживается не так хорошо:элементы должны быть выделены и отменены нажатием клавишSpace, но поддержка зависит от браузера

Атрибут step

Ввод атрибута задает допустимые интервалы чисел для поля ввода.

Пример: Если step=»3″, законными числами могут быть -3, 0, 3, 6 и т.д.

Совет: Этот атрибут можно использовать вместе с атрибутами max и min для создания диапазона допустимых значений.

Атрибут работает со следующими типами входных данных: number, range, date, datetime-local, month, time и week.

Пример

Поле ввода с заданными интервалами законных номеров:

<form>  <label for=»points»>Точки:</label>
  <input type=»number» id=»points» name=»points» step=»3″>
</form>

Примечание: Ограничения ввода не являются надежными, и JavaScript предоставляет множество способов добавления незаконных входных данных.
Чтобы безопасно ограничить ввод, он также должен быть проверен получателем (сервером)!

HTML input multiple values array

When a form with an input field that has the multiple attribute is submitted, the values entered by the user are sent as an array to the server. Each value is stored as an element in the array. The name of the input field is used as the key for the array.

Note the use of [] syntax in the field name to indicate that the values should be stored as an array. This allows the server-side code to access the values as an array and loop through them if necessary.

In PHP, for example, the values can be accessed using the $_POST superglobal like this:

Other server-side languages have similar ways of accessing form data submitted as an array.

Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: