Html типы ввода

Выбор даты

HTML 4 не включает выбор даты через календарь. JavaScript-фреймворки позволяют это обойти (Dojo, jQuery UI, YUI, Closure Library), но, конечно, каждое из этих решений требует «внедрения» фреймворка для любого встроенного календаря.

HTML5, наконец, определяет способ включить встроенный выбор даты без всяких скриптов. В действительности, их шесть: дата, месяц, неделя, время, дата + время и дата + время с часовым поясом.

Пока поддержка… скудна.

Поддержка выбора даты
Тип Opera Другие браузеры
type=»date» 9.0+
type=»month» 9.0+
type=»week» 9.0+
type=»time» 9.0+
type=»datetime» 9.0+
type=»datetime-local» 9.0+

Вот как Opera отображает <input type=»date»>:

Если вам нужно время вместе с датой, Opera также поддерживает <input type=»datetime»>:

Если вам нужен месяц плюс год (например, срок действия кредитной карты), Opera может отобразить <input type=»month»>:

Менее распространенным, но доступным является выбор недели в году через <input type=»week»>:

Последнее, но не менее важное, это выбор времени с :

Выбор даты с альтернативой

<form>
<input type=»date»>
</form>

<script>
var i = document.createElement(«input»);
i.setAttribute(«type», «date»);
if (i.type == «text») {
// Нет встроенной поддержки выбора даты 🙁
// Используйте Dojo/jQueryUI/YUI/Closure для ее создания,
// затем динамически замените элемент <input>
}
</script>

Labels and placeholders

TL;DR: To save you time, here’s the key point: don’t use the attribute if you can avoid it. If you need to label an element, use the <label> (en-US) element.

There are three seemingly similar ways to associate assistive text with an . However, they are actually quite different, and only one of them is always a good choice. Here we will look at each of them and learn best practices for providing the user with guidance when entering data into a form.

The <label> (en-US) element is the only way to provide explanatory information about a form field that is always appropriate (aside from any layout concerns you have). It’s never a bad idea to use a to explain what should be entered into an or <textarea> (en-US).

The attribute lets you specify a text that appears within the element’s content area itself when empty. It’s intended to be used to show an example input, rather than an explanation or prompt, but tends to be badly misused.

Here are two inputs that take a password, each with a placeholder:

The first one uses a placeholder string , demonstrating what a password might look like. And no, that’s not really a great password.

The second one uses a prompt string, as a placeholder. The first, and most obvious, problem with doing this is that as soon as the user types their first character, they no longer have a prompt explaining what that field is for.

That’s why, instead, you should use the <label> (en-US) element. The placeholder should never be required in order to understand your forms. While some people are able to remember what a given empty box is meant for after its only identifying text vanishes, others cannot.

If the user can’t understand your form if the placeholders are missing (say, in a browser that doesn’t support , or in the case above where the user starts typing then gets confused), you’re not using placeholders properly.

In addition, browsers with automatic page translation features may skip over attributes when translating. That means the may not get translated, resulting in important information not being translated.

If you feel like you need to use a placeholder, it’s possible to use both a placeholder and a label:

You can also just have plain text adjacent to the element, like this:

Please don’t do this. This doesn’t create a relationship between the prompt and the element, which is important for reasons we’ll get into in the next section.

In addition to the information provided above, there are a number of other reasons why is the best way to explain s:

  • The semantic pairing of and elements is useful for assistive technologies such as screen readers. By pairing them using the ‘s (en-US) attribute, you bond the label to the input in a way that lets screen readers describe inputs to users more precisely.
  • By pairing a with an , clicking on either one will focus the . If you use plaintext to «label» your input, this won’t happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions.
  • As web developers, it’s important that we never assume that people will know all the things that we know. The diversity of people using the web—and by extension your web site—practically guarantees that some of your site’s visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels.

Валидация форм

Поддержка валидации форм
IE Firefox Safari Chrome Opera iPhone Android
4.0+ 5.0+ 6.0+ 9.0+

В этой главе я говорил о новых элементах форм и новых возможностях, таких как автофокус, но я не упомянул, пожалуй, самую захватывающую часть форм HTML5: автоматическую проверку входных данных. Рассмотрим общие проблемы ввода адреса электронной почты в форме. Вероятно, у вас есть проверка на стороне клиента через JavaScript, после чего идет проверка на стороне сервера через PHP, Python или другой серверный язык. HTML5 никогда не сможет заменить проверку на стороне сервера, но он может когда-нибудь заменить проверку на стороне клиента.

Есть две большие проблемы, связанные с проверкой адреса электронной почты на JavaScript:

  1. Некоторое количество ваших посетителей (вероятно, около 10%) не включают JavaScript.
  2. Вы получите адрес неправильно.

Серьезно, вы получите адрес неправильно. Определение того, что набор случайных символов это корректный адрес электронной почты невероятно сложно. Чем сильнее вы смотрите, тем сложнее становится. Я уже говорил, что это очень, очень сложно? Не проще ли повесить эту головную боль на ваш браузер?

HTML5 также предлагает проверку веб-адресов с полем и чисел с

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

Не существует кода, включающего проверку форм в HTML5, это делается по умолчанию. Чтобы отключить проверку, используйте атрибут novalidate.

Не проверяй меня

Браузеры медленно включают поддержку проверки форм в HTML5. Firefox 4 будет иметь полную поддержку. К сожалению, Safari и Chrome реализуют лишь частично: они проверяют элементы форм, но не выводят никаких видимых сообщений, когда поля формы не проходит проверку. Другими словами, если вы введете неверную (или неправильно составленную) дату в , Safari и Chrome не отправит форму, но и не будет говорить вам, почему это не сделали. Они будут устанавливать фокус на поле, которое содержит недопустимое значение, но не отображать сообщение об ошибке, как Opera или Firefox 4.

Form types

How an works varies considerably depending on the value of its attribute, hence the different types are covered in their own separate reference pages. If this attribute is not specified, the default type adopted is .

The available types are as follows:

  • : A push button with no default behavior.
  • : A check box allowing single values to be selected/deselected.
  • : HTML5 A control for specifying a color. A color picker’s UI has no required features other than accepting simple colors as text ().
  • : HTML5 A control for entering a date (year, month, and day, with no time).
  • : HTML5 A control for entering a date and time, with no time zone.
  • : HTML5 A field for editing an e-mail address.
  • : A control that lets the user select a file. Use the accept attribute to define the types of files that the control can select.
  • : A control that is not displayed but whose value is submitted to the server.
  • : A graphical submit button. You must use the src attribute to define the source of the image and the alt attribute to define alternative text. You can use the height and width attributes to define the size of the image in pixels.
  • : HTML5 A control for entering a month and year, with no time zone.
  • : HTML5 A control for entering a number.
  • : A single-line text field whose value is obscured. Use the maxlength and minlength attributes to specify the maximum length of the value that can be entered.

    Note: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Firefox now implements multiple mechanisms to warn against insecure login forms — see Insecure passwords. Other browsers are also implementing similar mechanisms.

  • : A radio button, allowing a single value to be selected out of multiple choices.
  • : HTML5 A control for entering a number whose exact value is not important.
  • : A button that resets the contents of the form to default values.
  • : HTML5 A single-line text field for entering search strings. Line-breaks are automatically removed from the input value.
  • : A button that submits the form.
  • : HTML5 A control for entering a telephone number.
  • : A single-line text field. Line-breaks are automatically removed from the input value.
  • : HTML5 A control for entering a time value with no time zone.
  • : HTML5 A field for entering a URL.
  • : HTML5 A control for entering a date consisting of a week-year number and a week number with no time zone.

Some input types are now obsolete:

datetime (en-US): HTML5 This deprecated API should no longer be used, but will probably still work.This is an obsolete API and is no longer guaranteed to work. A control for entering a date and time (hour, minute, second, and fraction of a second) based on UTC time zone. This feature has been removed from WHATWG HTML.

Notes

If you want to present a custom error message when a field fails to validate, you need to use the available on (and related) elements. Take the following form:

The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the .

If you wanted to instead display custom error messages, you could use JavaScript like the following:

The example renders like so:

In brief:

  • We check the valid state of the input element every time its value is changed by running the method via the event handler.
  • If the value is invalid, an event is raised, and the event handler function is run. Inside this function we work out whether the value is invalid because it is empty, or because it doesn’t match the pattern, using an block, and set a custom validity error message.
  • As a result, if the input value is invalid when the submit button is pressed, one of the custom error messages will be shown.
  • If it is valid, it will submit as you’d expect. For this to happen, the custom validity has to be cancelled, by invoking with an empty string value. We therefore do this every time the event is raised. If you don’t do this, and a custom validity was previously set, the input will register as invalid, even if it current contains a valid value on submission.

Note: Firefox supported a proprietary error attribute — — for many versions, which allowed you set custom error messages in a similar way. This has been removed as of version 66 (see bug 1513890).

The allowed inputs for certain <input> types depend on the locale. In some locales, 1,000.00 is a valid number, while in other locales the valid way to enter this number is 1.000,00.

Firefox uses the following heuristics to determine the locale to validate the user’s input (at least for ):

  • Try the language specified by a / attribute on the element or any of its parents.
  • Try the language specified by any Content-Language HTTP header or
  • If none specified, use the browser’s locale.

You can use the attribute to specify the text for the label of the enter key on the virtual keyboard when your form is rendered on Firefox mobile. For example, to have a «Next» label, you can do this:

The result is:

Note the «Next» key in the lower-right corner of the keyboard.

Input Type Date

The is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

Example

<form>  <label for=»birthday»>Birthday:</label>  <input
type=»date» id=»birthday» name=»birthday»></form>

You can also use the and attributes to add restrictions to dates:

Example

<form>  <label for=»datemax»>Enter a date before
1980-01-01:</label>  <input type=»date» id=»datemax» name=»datemax»
max=»1979-12-31″><br><br>  <label for=»datemin»>Enter a date after
2000-01-01:</label>  <input type=»date» id=»datemin» name=»datemin»
min=»2000-01-02″></form>

HTML Tutorial

HTML HOMEHTML IntroductionHTML EditorsHTML BasicHTML ElementsHTML AttributesHTML HeadingsHTML ParagraphsHTML StylesHTML FormattingHTML QuotationsHTML CommentsHTML Colors
Colors
RGB
HEX
HSL

HTML CSSHTML Links
Links
Link Colors
Link Bookmarks

HTML Images
Images
Image Map
Background Images
The Picture Element

HTML TablesHTML Lists
Lists
Unordered Lists
Ordered Lists
Other Lists

HTML Block & InlineHTML ClassesHTML IdHTML IframesHTML JavaScriptHTML File PathsHTML HeadHTML LayoutHTML ResponsiveHTML ComputercodeHTML SemanticsHTML Style GuideHTML EntitiesHTML SymbolsHTML EmojisHTML CharsetHTML URL EncodeHTML vs. XHTML

Числа как счетчики

Следующий шаг: числа. Запрос числа более сложен, чем запрос адреса электронной почты или веб-адреса. Прежде всего, числа сложнее, чем вы думаете. Быстро выберите число. -1? Нет, я имел в виду число между 1 и 10,7 ½? Нет, нет, не дробь, тупица. π? Теперь вы просто выбрали иррациональное число.

Хочу заметить, у вас не часто спрашивают «просто число». Более вероятно, что будут просить число в определенном диапазоне. Вы можете только захотеть, чтобы в пределах этого диапазона были определенные типы чисел — может быть, целые числа, но не дроби или десятичные числа или что-то более экзотическое, например, кратные 10. HTML5 все это охватывает.

Выбрать число, почти любое

<input type=»number»
min=»0″
max=»10″
step=»2″
value=»6″>

Рассмотрим по одному атрибуту.

  • type=»number» означает, что это числовое поле.
  • min=»0″ указывает минимально допустимое значение для этого поля.
  • max=»10″ является максимально допустимым значением.
  • step=»2″ в сочетании с минимальным значением определяет допустимые числа в диапазоне: 0, 2, 4 и так далее, вплоть до максимального значения.
  • value=»6″ значение по умолчанию. Должно выглядеть знакомым, этот же атрибут всегда используется для определения значений полей формы. Я упоминаю здесь об этом для отправной точки, что HTML5 основывается на предыдущих версиях HTML. Вам не нужно переучиваться, чтобы делать то, что вы уже делали.

Это код числового поля. Имейте в виду, что все эти атрибуты являются необязательными. Если у вас задан минимум, но не максимум, можете указать атрибут min, но не max. По умолчанию значение шага равно 1 и вы можете опустить атрибут step, пока не понадобится другое значение шага. Если нет значения по умолчанию, то атрибут value может быть пустой строкой или даже вообще опущен.

Но HTML5 не останавливается на достигнутом. За ту же самую низкую, низкую цену свободы вы получаете эти удобные методы JavaScript.

  • input.stepUp(n) повышает значение поля на n.
  • input.stepDown(n) понижает значение поля на n.
  • input.valueAsNumber возвращает текущее значение как число с плавающей точкой (свойство input.value это всегда строка).

Проблемы с отображением? Ну, правильный интерфейс по управлению числами в браузерах реализован по-разному. На iPhone, где набор имеет сложности, браузер опять оптимизирует виртуальную клавиатуру для ввода чисел.

В настольной версии Оперы поле type=»number» отображается как счетчик с небольшими стрелками вверх и вниз, которые можно нажать для изменения значений.

Опера уважает атрибуты min, max и step, поэтому вы всегда добьетесь приемлемого числового значения.  Если вы увеличите значение до максимума, стрелка вверх в счетчике становится серой.

Как и со всеми другими полями ввода, что я обсуждал в этой главе, браузеры, которые не поддерживают type=»number», будут относиться к нему как к type=»text». Значение по умолчанию будет отображаться в поле (так как оно хранится в атрибуте value), но другие атрибуты, такие как min и max будут игнорироваться. Вы можете свободно реализовать их самостоятельно или использовать JavaScript-фреймворк, который уже реализует управление счетчиком. Вначале проверьте встроенную поддержку HTML5, как здесь.

if (!.inputtypes.number) {
// нет встроенной поддержки для поля type=number
// может попробовать Dojo или другой JavaScript-фреймворк
}

Input Cards

Header

Example

<div class=»w3-card-4″><div class=»w3-container
w3-green»>  <h2>Header</h2></div><form class=»w3-container»><label>First Name</label><input class=»w3-input»
type=»text»>
<label>Last Name</label><input class=»w3-input»
type=»text»></form></div>

Colored Labels

Use any of the w3-text-color classes to color your labels:

Example

<form class=»w3-container»><label
class=»w3-text-blue»><b>First Name</b></label>
<input class=»w3-input w3-border» type=»text»> 
<label
class=»w3-text-blue»><b>Last Name</b></label>
<input class=»w3-input w3-border» type=»text»><button class=»w3-btn
w3-blue»>Register</button> </form>

Add the w3-border class to create bordered inputs:

Example

<input class=»w3-input w3-border»
type=»text»>

Rounded Borders

Use any of the w3-round classes to create rounded borders:

Example

<input class=»w3-input w3-border w3-round»
type=»text»><input class=»w3-input w3-border
w3-round-large»
type=»text»>

Borderless Input

The w3-input class has a bottom border by default. If you want a borderless input, add the w3-border-0 class:

Example

<form class=»w3-container w3-light-grey»>  <label>First
Name</label>  <input class=»w3-input w3-border-0″ type=»text»>  <label>Last Name</label>  <input class=»w3-input
w3-border-0″ type=»text»></form>

Input Form

Example

<div class=»w3-container w3-teal»>  <h2>Input Form</h2></div><form class=»w3-container»>  <label class=»w3-text-teal»><b>First Name</b></label> 
<input class=»w3-input w3-border w3-light-grey» type=»text»>  <label class=»w3-text-teal»><b>Last Name</b></label> 
<input class=»w3-input w3-border w3-light-grey» type=»text»>  <button class=»w3-btn w3-blue-grey»>Register</button></form>

Hoverable inputs

The w3-hover-color classes adds a background color to the input field on mouse-over:

Example

<input class=»w3-input w3-hover-green» type=»text»><input class=»w3-input
w3-border w3-hover-red» type=»text»><input class=»w3-input
w3-border w3-hover-blue» type=»text»>

Animated Inputs

The w3-animate-input class transforms the width of an input field to 100% when it gets focus:

Example

<input class=»w3-input w3-animate-input»
type=»text» style=»width:30%»>

Example

<input class=»w3-check» type=»checkbox» checked=»checked»>
<label>Milk</label><input class=»w3-check»
type=»checkbox»><label>Sugar</label>
<input class=»w3-check» type=»checkbox» disabled>
<label>Lemon (Disabled)</label>

Example

<input class=»w3-radio» type=»radio» name=»gender» value=»male» checked>
<label>Male</label><input class=»w3-radio»
type=»radio» name=»gender» value=»female»><label>Female</label><input class=»w3-radio»
type=»radio» name=»gender» value=»» disabled><label>Don’t know (Disabled)</label>

Select Options

Example

<select class=»w3-select» name=»option»>  <option value=»» disabled
selected>Choose your option</option>  <option value=»1″>Option
1</option>  <option value=»2″>Option 2</option>  <option
value=»3″>Option 3</option></select>

Example

<select class=»w3-select w3-border» name=»option»>

Form Elements in a Grid

In this example, we use W3.CSS’ Responsive Grid System to make the inputs appear on the same line (on smaller screens, they will stack horizontally with 100% width).
You will learn more about this later.

Example

<div class=»w3-row-padding»>  <div class=»w3-third»>   
<input class=»w3-input w3-border» type=»text» placeholder=»One»> 
</div>  <div class=»w3-third»>    <input
class=»w3-input w3-border» type=»text» placeholder=»Two»>  </div> 
<div class=»w3-third»>    <input class=»w3-input
w3-border» type=»text» placeholder=»Three»>  </div></div>

Grid with Labels

Example

<div class=»w3-row-padding»>  <div class=»w3-half»>   
<label>First Name</label>    <input
class=»w3-input w3-border» type=»text» placeholder=»Two»>  </div> 
<div class=»w3-half»>    <label>Last
Name</label>    <input class=»w3-input
w3-border» type=»text» placeholder=»Three»>  </div></div>

❮ Previous
Next ❯

HTML тег

Все элементы тега форм создаются с помощью тега <input>.

Синтаксис <input>

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

  • name=»name_field» — параметр для задания имени конкретному input. Это нужно, чтобы при дальнейшей обработке данных формы можно было получить значение этого поля.
  • type=»значение» — отвечает за тип элемента, т.е. что именно будет представлять из себя поле. И здесь есть множество возможных значений:

    • text — текстовое поле. Одно из самых часто используемых значений
    • password — текстовое поле, но с той особенностью, что при вводе символы скрыты
    • radio — радиокнопки
    • checkbox — переключатели
    • submit — кнопка для отправки значений формы (управление передается на адрес указанный в адрес, указанный в action атрибута формы)
    • reset — кнопка для очистки всей формы
    • hidden — скрытое поле
    • button — кнопки для обработки каких-то действий (не путать с submit!)
    • file — для загрузки файлов на сервер
    • image — поле с изображением (используется крайне редко)
  • value=»значение» — указывается значение по умолчанию

Теперь разберем более подробно каждый элемент

Code Example

The most basic form field

The element is the fundamental form element for gathering user info through forms. The vast majority of form fields are the element, and there are only a handful of form field types — , for example — that are actually a different element. From range sliders to date selectorsto submit buttons, the element covers a lot of different cases.

Because of that, it also has a huge number of attributes and potential values. Many of them are only applicable to certain types of inputs. There are a handful that are universally important, though:

  • The attribute determines the type, or style, of the element. This is the most important attribute, as it determines everything else about how the element behaves.
  • The is used in conjunction with the attribute to send user data to the server.
  • Setting the attribute in your HTML document allows you to pre-specify the content of the input field, or its default value
  • Both and stop the user from editing the value of the input, but there are some important difference to know about.
  • Including the stops the form from accepting submission if the field has no value.

See the lists below for more details about options.

Adam Wood

Input Type Hidden

The
defines a hidden input field (not visible to a user).

A hidden field let web developers include data that cannot be seen or
modified by users when a form is submitted.

A hidden field often stores what database record that needs to be updated
when the form is submitted.

Note: While the value is not displayed to the user in the
page’s content, it is visible (and can be edited) using any browser’s developer
tools or «View Source» functionality. Do not use hidden inputs as a form of
security!

Example

<form>  <label for=»fname»>First name:</label> 
<input type=»text» id=»fname» name=»fname»><br><br>  <input
type=»hidden» id=»custId» name=»custId» value=»3487″>  <input
type=»submit» value=»Submit»></form>

See also

  • Other form-related elements: <form> (en-US), <button> (en-US), <datalist> (en-US), <legend> (en-US), <label> (en-US), <select> (en-US), <optgroup> (en-US), <option> (en-US), <textarea> (en-US), <keygen> (en-US), <fieldset> (en-US), , <progress> (en-US) and <meter> (en-US).
  • Form constraint validation
  • Cross-browser HTML5 placeholder text
  • The CSS (en-US) property
  • In certain cases (typically involving non-textual inputs and specialized interfaces), the element is a replaced element. When it is, the position and size of the element’s size and positioning within its frame can be adjusted using the CSS (en-US) and properties

Обработка исключений ввода

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

Вот такой код считается небезопасным:

Запустим его и введем следующее:

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

Вот как можно сделать код безопаснее и обработать ввод:

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

Вот так будет выглядеть вывод с исключением.

Такой код можно объединить с другой конструкцией, например, циклом for, чтобы убедиться, что код будет выполняться постоянно, до тех пор, пока пользователь не введет те данные, которые требуются.

Окно поиска

Итак, поиск. Не только поиск от Google или Yahoo (ну, те тоже). Подумайте о любом окне поиска, на любой странице, на любом сайте. Амазон имеет окно поиска, Яндекс имеет окно поиска, большинство блогов тоже. Как они сделаны? <input type=»text»>, как и любое другое текстовое поле в сети. Давайте это исправим.

Поиск нового поколения

<form>
<input name=»q» type=»search»>
<input type=»submit» value=»Найти»>
</form>

В некоторых браузерах вы не заметите никакого отличия от обычного текстового поля. Но если вы используете Safari на Mac OS X, это будет выглядеть так.

Нашли разницу? Поле ввода имеет закругленные углы! Я знаю, знаю, вы вряд ли можете сдержать свои чувства. Но подождите, это еще не все! Когда вы начнете вводить в поле type=»search» Safari вставит небольшую кнопку «x» с правой стороны окна. Нажатие на «x» очищает содержимое поля. Google Chrome, который имеет под капотом ту же технологию, ведет себя так же. Обе эти маленькие хитрости выглядят и ведут себя аналогично родному поиску в iTunes и других клиентских приложениях Mac OS X.

Apple.com использует <input type=»search»> для поиска по своему сайту, чтобы помочь сайту передать «маколюбное» ощущение. Но здесь нет ничего специфичного для Маков. Это просто код, так что каждый браузер на любой платформе может выбрать, как отображать в соответствии с соглашениями платформы. Как и со всеми другими новыми типами, браузеры, которые не признают type=»search» будут относиться к нему как type=»text», так что нет абсолютно никаких причин не начать использовать type=»search» для всех ваших окон поиска прямо сегодня.

Профессор Маркап говорит

По умолчанию Safari не применяет к большинство стилей. Если вы хотите заставить Safari понимать поле для поиска как обычное текстовое поле (чтобы применить собственные стили), добавьте это правило к вашей таблице стилей.

input {
-webkit-appearance: textfield;
}

Спасибо Джону Лейну за обучение меня этому трюку.

Hoverable inputs

The w3-hover-color classes adds a background color to the input field on mouse-over:

Example

<input class=»w3-input w3-hover-green» type=»text»><input class=»w3-input
w3-border w3-hover-red» type=»text»><input class=»w3-input
w3-border w3-hover-blue» type=»text»>

Animated Inputs

The w3-animate-input class transforms the width of an input field to 100% when it gets focus:

Example

<input class=»w3-input w3-animate-input»
type=»text» style=»width:30%»>

Example

<input class=»w3-check» type=»checkbox» checked=»checked»>
<label>Milk</label><input class=»w3-check»
type=»checkbox»><label>Sugar</label>
<input class=»w3-check» type=»checkbox» disabled>
<label>Lemon (Disabled)</label>

Example

<input class=»w3-radio» type=»radio» name=»gender» value=»male» checked>
<label>Male</label><input class=»w3-radio»
type=»radio» name=»gender» value=»female»><label>Female</label><input class=»w3-radio»
type=»radio» name=»gender» value=»» disabled><label>Don’t know (Disabled)</label>

Select Options

Example

<select class=»w3-select» name=»option»>  <option value=»» disabled
selected>Choose your option</option>  <option value=»1″>Option
1</option>  <option value=»2″>Option 2</option>  <option
value=»3″>Option 3</option></select>

Example

<select class=»w3-select w3-border» name=»option»>

Form Elements in a Grid

In this example, we use W3.CSS’ Responsive Grid System to make the inputs appear on the same line (on smaller screens, they will stack horizontally with 100% width).
You will learn more about this later.

Example

<div class=»w3-row-padding»>  <div class=»w3-third»>   
<input class=»w3-input w3-border» type=»text» placeholder=»One»> 
</div>  <div class=»w3-third»>    <input
class=»w3-input w3-border» type=»text» placeholder=»Two»>  </div> 
<div class=»w3-third»>    <input class=»w3-input
w3-border» type=»text» placeholder=»Three»>  </div></div>

Grid with Labels

Example

<div class=»w3-row-padding»>  <div class=»w3-half»>   
<label>First Name</label>    <input
class=»w3-input w3-border» type=»text» placeholder=»Two»>  </div> 
<div class=»w3-half»>    <label>Last
Name</label>    <input class=»w3-input
w3-border» type=»text» placeholder=»Three»>  </div></div>

❮ Previous
Next ❯

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

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

Adblock
detector