Html radio в виде кнопки. Радиокнопки и чекбоксы в HTML, их теги и атрибуты. Особенности работы полей input
Однажды, у меня возникла задача, сделать на форме сайта выбор одного из нескольких цветов. Казалось бы, нет ничего проще. Элемент radiobutton , как нельзя лучше, подходит для этой задачи, нужно только чуть-чуть его кастомизировать. Тут-то и начинаются проблемы. Дело в том, что отрисовкой элементов radiobutton и checkbutton управляет не браузер, а ОС. Соответственно, большинство свойств CSS (например, background-color) на них не действует.
В интернете я нашел множество способов кастомизации radiobutton , но все они показались мне слишком сложными, поэтому я решил придумать свой.
Моя идея основана на том факте, что когда пользователь кликает по подписи label , radiobutton переключается. Значит можно кастомизировать не radiobutton , а label .
Рассмотрим пример кода HTML:
Здесь нет ничего необычного. Обычные radiobutton и подписи к ним.
Теперь CSS: // скрываем radiobutton
input{display: none;}
// кастомизируем label
label{
width: 20px;
height: 20px;
}
label.blue{background-color: blue;}
label.cyan{background-color: #00ffff;}
// Для выбранного объекта
input:checked+label{
border: black solid 2px;
}
Здесь мы скрываем radiobutton и рисуем, как нам хочется label . Рисуем label для отмеченного состояния input:checked+label . Всё просто и элегантно.
На этом можно было бы закончить пост, если бы не одно «но».
Пара гнилых помидоров в сторону Apple
Мир был бы хорош и прекрасен, если бы в нём не было одной корпорации у которой особый путь развития. Это корпорация Apple, которая отказывает своим пользователям в праве тыкать по label . В следствии чего, мой способ не работает на iPhone и iPad. Самое интересное, что Safari на Windows пережевывает всё правильно. К сожалению не было под рукой ни одного iMac, чтобы проверить.
Специально для хипстеров пришлось таки применить JS (код рассчитан на использование в связке с jQuery): var deviceAgent = navigator.userAgent.toLowerCase();
var iOS = deviceAgent.match(/(iphone|ipod|ipad)/);
if (iOS) {
$("label").click(function (event) {
$("#" + $(event.target).attr("for")).attr("checked", true).change();
});
}
Пример использования
Long Twit — простой сервис, который рендерит текст в картинку и отправляет в Twitter. Можно выбрать цвет текста и фона.
В прошлом уроке мы изучили понятие формы. Её основная задача - объединить формы ввода данных определённого типа. Например, форма может объединить данные анкеты, теста и тд. В этом уроке мы научимся делать сами поля ввода!
За заполнение формы отвечает специальный тег
, у него есть атрибут type, который позволяет создать определённые заполняемые поля: текстовые поля, радиокнопки, флажки, списки, кнопки. Повторяю, все перечисленные вверху элементы доступны лишь в одном теге - .
Тег в HTML
- это одиночный тег, с помощью которого можно создавать определённые элементы документа (текстовые поля, радиокнопки, флажки, списки, кнопки), которые предназначены для заполнения прямо на html-странице.
Ниже пример
работы в HTML
У тега имеется несколько очень важных значений атрибутов.
name
- атрибут, который следует всегда задавать для элемента, чтобы обработчик (скрипт) понимал, input с каким именем он обрабатывает.
Так скрипт обработки поймёт, что это два разных поля.
type
- данный атрибут отвечает за указание типа поля. Как уже говорилось ранее, при определённом типе input может стать радиокнопкой, флажком, списком, кнопкой, текстовым поля.
size
- атрибут, указывающий размер для текстового поля, когда type указан как text. Указанные данные воспринимаются как ширина поля.
Тег имеет много других атрибутов, например, id (уникальный идентификатор поля, нужен, например, при работе с JavaScript), value (рассмотрим ниже). В статье я указал все основные атрибуты и значения, которых вполне достаточно для работы с полями input.
Атрибут type для input
Теперь давайте подробнее разберем атрибут type
и его значения:
text
- значение атрибута указывает на то, что будет отображено обычное текстовое поле, изначально доступное для изменения.
Атрибут value
не обязателен, его можно вообще не указывать. Однако, если нужно указать значение по умолчанию, которое будет изначально отображаться в поле, то его следует заполнить.
password
- превращает input в поле для заполнения пароля. Отличие от text заключается в том, что вводимые данные будут отображаться как звёздочки, а после заполнения всей формы браузер будет понимать, что в этом поле пароль и будет спрашивать, нужно ли его сохранить.
submit
- подобное значение атрибута type определяет input как кнопку, при нажатии которой будет прорабатываться определённый сценарий (что такое сценарий вы узнаете позже, изучив языки PHP и JavaScript). Кнопка используется для того, чтобы отправить данные из форм к обработчику, написанному, например, на вышеуказанных языках. Есть и другие, но указал самые популярные.
reset
- это ещё один вид кнопки, который обнуляет все значения в форме. после её нажатия их нужно будет заполнить заново.
radio
- Данное значение создает радиокнопку, то есть переключатель. Используется, как правило, для значений с небольшим количеством вариантов. Например, выбрать пол, интервал с возрастом и тп. выглядит следующим образом:
У атрибута type задано значение radio - это радиокнопка. В значение value записывается та фраза или слово, которое вы хотите получить, если кто-то выбрал определенную радиокнопку и отправил данные.
Бывают и другие случаи, когда пользователю нужно выбрать несколько вариантов ответа. В этом случае используется уже не радиокнопка (принимает только один вариант), а флажок или чекбокс.
checkbox
- это поле, которое работает так же как и радиокнопка. С разницей лишь в том, что можно выделить несколько чекбоксов в качестве вариантов ответа. Также как и с радиокнопкой, если к вопросу принадлежат несколько чекбоксов, то у них атрибут name должен быть соответственно одинаково заполнен. В value соответственно будет указано значение выбранного поля.
Особенности работы полей input
Тут предлагаю разобрать некоторые вопросы, с которыми также можете столкнутmcя в начале в работе с input.
Как сделать так, чтобы у пользователя сразу был выбран ответ (чекбокс или радиокнопка)?
Для этого существует одиночный атрибут checked. Его нужно указать в конце тега input. Так как атрибут одиночный, то значений у него никаких нет. Надо лишь добавить его в элемент input. Например, как в записи ниже:
Как сделать так, чтобы напротив чекбокса или радиокнопки был виден текст, поясняющий данный выбор?
Для этого перед и после радиокнопки или чекбокса пишем тег
Соответственно указываете в теге label, открывающем и закрывающем, сам чекбокс и нужные слова. И внимание! Даже если пользователь нажмёт на слово, то чекбокс всё равно будет выделен.
Код HTML
Пример использования полей input в HTML
This page contains code for creating an HTML radio button. It also provides an explanation of radio buttons. Feel free to copy and paste the code into your own website or blog.
You create a radio button with the HTML tag. You add type="radio" to specify that it"s a radio button. This is because the tag does more than create radio buttons. It also allows you to make text input controls, submit buttons, checkboxes, and more.
Anyway, here is the code and some information on creating a radio button.
Basic Radio Button
This example uses the tag to create a basic radio button. Within the code, we use type="radio" to set the control to a radio button.
You will notice that, although all radio buttons had different values (i.e. within the value attribute) all radio buttons shared the same name (within the name attribute). I"ll explain how this works shortly. In the meantime, let"s look at multiple groups of radio buttons.
Groups of Radio Buttons
Here are two groups of radio buttons. Notice once again that the radio buttons in each group shares the name. The first group has a name of "preferred_color" and the second group has a name of "preferred_item".
Important points to note about radio buttons:
All radio buttons within a group must share the same name. That is, the value of the name attribute should be the same. For example, all three radio buttons in the "Preferred Color" group have name="preferred_color" .
All radio buttons within a group should have a different value for the value attribute. For example, if one radio button has value="red" , none of the others in that group should have a value of red, as this would defeat the purpose of having the extra radio button.
The "label" for each radio button is determined by the text next to the radio button (not the value attribute). The value attribute is used by the form handler.
Understanding Radio Buttons
When you first learn how to create a radio button, you may find it a little difficult to understand how the name and value attributes work. This is probably because radio buttons are a little different to most form elements. I"ll explain.
The whole purpose of a radio button is to enable the user to make one selection - and one only - from a list. If you wanted the user to make multiple selections, you wouldn"t use a radio button - you"d use a checkbox.
Anyway, because the user can only make one selection from our group of radio buttons, all radio buttons in that group need to share the same name. This is how we group the list together - they all share the same name. This tells the form handler the name of the group, and the value of the selected radio button.
For example, if you want users to choose between a group of colors, you would create a radio button for each color. You would give all radio buttons the same name (for example, "preferred_color"), but you would give each radio button a different value (for example, "red").
So, let"s say a user submits a form that sends an email to the webmaster. The user selects their preferred color from a radio button and clicks the submit button. The webmaster might receive an email that looks like this:
I"m sure you could think of better things to do than to simply ask for your users" favorite color, but hopefully you get the idea! In this case, the form handler (i.e. a server-side script), has processed the form and emailed the name of the group (Preferred_color), and the value that was selected (Red).
Последнее обновление: 08.04.2016
Флажок
Флажок представляет элемент, который может находиться в двух состояниях: отмеченном и неотмеченном. Флажок создается с помощью элемента input
с атрибутом type="checkbox"
:
Чекбокс в HTML5
Изучаемые технологии
Атрибут checked
позволяет установить флажок в отмеченное состояние.
Переключатели
Переключатели или радиокнопки похожи на флажки, они также могут находиться в отмеченном или неотмеченном состоянии. Только для переключателей можно создать
одну группу, в которой одновременно можно выбрать только один переключатель. Например:
Радиокнопки в HTML5
Для создания радиокнопки надо указать атрибут type="radio" . И теперь другой атрибут name указывает не на имя элемента, а на имя
группы, к которой принадлежит элемент-радиокнопка. В данном случае у нас две группы радиокнопок: gender и tech . Из каждой группы
мы можем выбрать только один переключатель. Опять же чтобы отметить радиокнопку, у нее устанавливается атрибут checked:
Важное значение играет атрибут value , который при отправке формы позволяет серверу определить, какой именно переключатель был отмечен.
Let"s add a little bit of code to our example so we can examine the data generated by this form. The HTML is revised to add a element represents preformatted text which is to be presented exactly as written in the HTML file.">
block to output the form data into:
Using radio inputs
We already covered the fundamentals of radio buttons above. Let"s now look at the other common radio-button-related features and techniques you may need to know about.
Selecting a radio button by default
To make a radio button selected by default, you simply include checked attribute, as shown in this revised version of the previous example:
In this case, the first radio button is now selected by default.
Note
: If you put the checked attribute on more than one radio button, later instances will override earlier ones; that is, the last checked radio button will be the one that is selected. This is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked.
Providing a bigger hit area for your radio buttons
In the above examples, you may have noticed that you can select a radio button by clicking on its associated element represents a caption for an item in a user interface.">
Beyond accessibility, this is another good reason to properly set up
Validation
Radio buttons don"t participate in constraint validation; they have no real value to be constrained.
Styling radio inputs
The following example shows a slightly more thorough version of the example we"ve seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this:
There"s not much new to note here except for the addition of element is used to group several controls as well as labels (
Most notable here is the use of the -moz-appearance property (with prefixes needed to support some browsers). By default, radio buttons (and checkboxes) are styled with the operating system"s native styles for those controls. By specifying appearance: none , you can remove the native styling altogether, and create your own styles for them. Here we"ve used a border along with border-radius and a transition to create a nice animating radio selection. Notice also how the ), checkbox (), or option (
Compatibility note
: If you wish to use the appearance property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword none does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers.
Notice that when clicking on a radio button, there"s a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you"d want in a real web application, but it definitely shows off the possibilities.
Specifications
Specification
Status
Internet Explorer
Opera
Safari
Android webview
Chrome for Android
Firefox for Android
Opera for Android
Safari on iOS
Samsung Internet
type="radio"
Chrome
Full support
Yes
Edge
Full support
Yes
Firefox
Full support
Yes
IE
Full support
Yes
Opera
Full support
Yes
Safari
Full support
Yes
WebView Android
Full support
Yes
Chrome Android
Full support
Yes
Firefox Android
Full support
4
Opera Android
Full support
Yes
Safari iOS
Full support
Yes
Samsung Internet Android
?
Legend
Full support
Full support
Compatibility unknown
Compatibility unknown
See also
element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> and the elements."> HTMLInputElement interface that implements it.
or a
element."> RadioNodeList : the interface that describes a list of radio buttons