Radio Button In HTML
You may have filled many forms online requiring you to select an option out of a few options in which only one can be selected, like gender selection or a simple "yes or no " question. These options are made using radio buttons in HTML.
Scope
- This article explains you about the Radio buttons in HTML with examples.
- This article will teach you how to add Radio buttons in HTML forms.
- Different attributes of the Radio buttons are explained in this article.
- After reading this article you will know the difference between Radio buttons and Checkboxes.
Introduction
These days almost all websites require HTML forms to collect user information. We can use different methods to take input from the users by using HTML <input> element. One such method is taking input by providing users with the options to choose from. We use HTML Radio buttons for this purpose we provide users a bunch of options out of which they can select their response.
As in the above example, a radio button is used to ask the user about the payment options. A radio button is generally renderd as a small circle with a solid circle inside it when selected.
What Is Radio Button In HTML?
A radio button is a graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options. The singular property of a radio button makes it distinct from checkboxes, where the user can select and unselect any number of items.
Syntax
To add radio buttons in a webpage, We use the <input> element with type attribute is set to “radio”. But it will create a rather simple radio button. So we use different Radio attributes present to us.
As shown in the example below, we used the name attribute to group the buttons together so that only one option can be chosen, without the name attribute we can not group different buttons together, therefore, user will be able to choose more than one option. The value attribute is used to send the value of the selected option to the server.
EXAMPLE
Output
Attributes for Radio Button
With global attributes that are used with <input> element, radio inputs also support the following attributes.
| Attribute | Description |
|---|---|
| Type | It indicates the input type, It is added to create a user defined button. In this case, the input type is set as "Radio". |
| Name | It indicates the name of input elements. Different radio buttons with the same name are grouped together. |
| Value | It sends the value of the selected option to the server. |
| Checked | It is used to select an option by default if nothing is chosen by the user. |
Examples
Example 1: Checked Radio Button
If from a group of options at least one option has to be selected in that case we use the checked attribute to set an option as the default value.
For instance, in the below example we must choose atleast one direction, and the option 1 that is the north direction is set as the default option.
Example
As we can see option1 i.e NORTH is selected by default.
Output
NOTE — When you set multiple options as default the latter one overrides the previous one in the code because you can set only one option as default.
Example 2: Disabled Radio Button
We can disable a radio button by using the disabled property of HTML DOM. A disabled button is unclickable and unresponsive. A disabled radio button is rendered grey in color by the browser. The disabled attribute uses boolean values to decide whether a button should be disabled or not ( disabled=true|false ) true represents that button is disabled and false represents it is not disabled. By default disabled is set to false. We will use javascript for this. Javascript code is enclosed inside the script tags.
Example
Output
In the above example, we first created a button "direction" after that we created a DISABLE button which will disable the button by invoking the disable_button() method.
Then the disable_button() method will set the disabled property to true by accessing the radio button "Directions" using the getElementById() method as shown below.
Example 3: Groups of Radio Buttons
We make groups of radio buttons so that out of present options only one can be selected. We can put different radio buttons in a group using the name attribute. All the buttons in a group must have the same name attribute.
Example
Output
Example 4: Radio Button Style
There are a few disadvantages of the using default radio button style, for instance, different browsers have different appearances of the default radio buttons. We can tackle this problem by creating custom radio buttons using CSS.
Steps to create custom radio buttons:
a) Base HTML
This is the base HTML code for our radio button we will add CSS to style it further.
Output
b) Customizing the Container of Radio Buttons
In this we define font size, text alignment, position, etc for the radio buttons as shown below.
c) Hide the Original Radio Button
We have to hide the original radio button but keep it technically accessible. We can do this by simply setting the appearance attribute as none.
d) Custom Radio Button Style
In this section we will customize the radio boxes. we will define properties like background color, dimensions, etc. we will also add the hover effect which will give a specified background color on hovering the cursor over radio box.
e) Checked State
In this section we will style the radio box for checked state.
f) Putting it All Together
After combining the base HTML code with CSS we will get the following output.
Output
How To Add Radio Buttons In Form Using HTML?
We can add radio buttons in our HTML form using input element with type as radio, below are the few steps which we can follow:
Step1: Use <input> element with type specified as radio. for example:
Output
Step2: Using the name attribute, group the buttons together so that only one option can be chosen. For example:
Output
Step3: Use the value attribute to give a value to an option that is to be sent to the server. For example:
Now our radio button is complete and can be used in forms.
Radio Buttons vs Checkboxes
While both Radio buttons and checkboxes are used to take input from the user they are quite different from each other.
<input type=»radio»>
<input> типа radio обычно используются в группах переключателей — наборах переключателей, описывающих набор связанных опций.
Одновременно может быть выбрана только одна радиокнопка в данной группе.Радиокнопки обычно отображаются в виде небольших кружков,которые при выборе заливаются или подсвечиваются.
Try it
Их называют радио-кнопками,потому что они выглядят и работают аналогично кнопкам на старомодных радиоприемниках,как показано ниже.
Примечание. Флажки похожи на переключатели, но с одним важным отличием: переключатели предназначены для выбора одного значения из набора, тогда как флажки позволяют включать и отключать отдельные значения. Если существует несколько элементов управления, радиокнопки позволяют выбрать один из них, тогда как флажки позволяют выбрать несколько значений.
Value
Атрибут value — это строка, содержащая значение переключателя. Это значение никогда не показывается пользователю их пользовательским агентом . Вместо этого он используется для определения того, какой переключатель в группе выбран.
Определение радиогруппы
Радиогруппа определяется присвоением каждой радиокнопке одного и того же name . Как только радиогруппа установлена, выбор любой радиокнопки в этой группе автоматически отменяет выбор любой выбранной радиокнопки в той же группе.
Вы можете иметь столько радиогрупп на странице, сколько захотите, при условии, что каждая имеет собственное уникальное name .
Например, если в вашей форме требуется запросить у пользователя предпочтительный метод связи, вы можете создать три переключателя, каждый со свойством name , установленным для contact но один со значением email , один со значением phone и один со значением mail . Пользователь никогда не видит value или name (если вы явно не добавили код для его отображения).
Получившийся HTML выглядит следующим образом:
Здесь вы видите три переключателя, для каждой из которых задано name для contact а для каждой — уникальное value которое однозначно идентифицирует индивидуальный переключатель в группе. Каждый из них также имеет уникальный id , который используется атрибутом элемента <label> for связывания меток с переключателями.
Вы можете попробовать этот пример здесь:
Представление данных радиогруппы
Когда вышеуказанная форма отправляется с выбранным переключателем, данные формы включают запись в форме contact=value . Например, если пользователь нажимает кнопку с зависимой фиксацией «Телефон», а затем отправляет форму, данные формы будут включать строку contact=phone .
Если опустить value атрибута в HTML, поданная форма данных присваивает значение on группе. В этом сценарии, если пользователь щелкнет опцию «Телефон» и отправит форму, результирующие данные формы будут contact=on , что бесполезно. Так что не забудьте установить атрибуты value !
Примечание. Если при отправке формы переключатель не выбран, радиогруппа вообще не включается в отправленные данные формы, поскольку нет значения для отчета.
Довольно редко на самом деле требуется разрешить отправку формы без какой-либо из выбранных радиокнопок в группе, поэтому обычно разумно иметь одно значение по умолчанию для checked состояния. См. Раздел Выбор переключателя по умолчанию ниже.
Давайте добавим немного кода в наш пример, чтобы мы могли изучить данные, сгенерированные этой формой. HTML изменен, чтобы добавить блок <pre> для вывода данных формы в:
Затем мы добавляем некоторый JavaScript, чтобы настроить прослушиватель событий для события submit , которое отправляется, когда пользователь нажимает кнопку «Отправить»:
Попробуйте этот пример и убедитесь, что для contact группы никогда не бывает более одного результата .
Additional attributes
В дополнение к общим свойствам совместно используемых всеми <input> элементов, radio входы поддерживают следующие атрибуты.
Булевский атрибут,который,если присутствует,указывает,что данная радиокнопка является выбранной по умолчанию в группе.
В отличии от других браузеров, Firefox по умолчанию сохраняется динамическое состояние проверяется из <input> по загрузке страницы. Используйте атрибут autocomplete для управления этой функцией.
value атрибута является тот , который все <input> Отправить; однако он служит особой цели для входных данных типа radio : когда форма отправляется, на сервер отправляются только переключатели, которые в настоящее время проверены, а сообщаемое значение является value атрибута value . Если value не указано иное, то строка on умолчанию. Это показано в разделе « Значение» выше.
Использование радио входов
Мы уже рассказали об основах радиокнопок выше.Теперь давайте рассмотрим другие распространенные функции и приемы,связанные с радиокнопками,о которых вам может понадобиться знать.
Выбор радиокнопки по умолчанию
Чтобы сделать переключатель выбранным по умолчанию, вы включаете атрибут checked , как показано в этой исправленной версии предыдущего примера:
В этом случае первая радиокнопка теперь выбрана по умолчанию.
Примечание. Если вы поместите атрибут checked более чем на одну радиокнопку, более поздние экземпляры переопределят более ранние; то есть последний checked переключатель будет выбранным. Это связано с тем, что одновременно может быть выбрана только одна радиокнопка в группе, и пользовательский агент автоматически отменяет выбор других каждый раз, когда новая кнопка помечается как отмеченная.
Обеспечивая большую область попадания для ваших радиокнопок
В приведенных выше примерах вы могли заметить, что вы можете выбрать переключатель, щелкнув связанный с ним элемент <label> , а также сам переключатель. Это действительно полезная функция меток HTML-форм, которая упрощает пользователям выбор нужного параметра, особенно на устройствах с маленьким экраном, таких как смартфоны.
Помимо доступности, это еще одна веская причина для правильной настройки элементов <label> в ваших формах.
Validation
Радио кнопки не участвуют в проверке ограничений;они не имеют реальной ценности,которую можно было бы ограничить.
Стилизация радиовходов
В следующем примере показан чуть более подробный вариант примера,который мы видели на протяжении всей статьи,с некоторой дополнительной стилизацией,и с лучшей семантикой,созданной за счет использования специализированных элементов.HTML выглядит следующим образом:
Здесь особо нечего отметить, за исключением добавления элементов <fieldset> и <legend> , которые помогают красиво и семантически сгруппировать функциональность.
Вовлеченные CSS немного более значимы:
Наиболее примечательным здесь является использование свойства appearance (с префиксами, необходимыми для поддержки некоторых браузеров). По умолчанию радиокнопки (и флажки ) имеют собственный стиль операционной системы для этих элементов управления. Указав appearance: none , вы можете полностью удалить собственные стили и создать для них свои собственные стили. Здесь мы использовали border вместе с border-radius и transition чтобы создать красивый анимированный выбор радио. Также обратите внимание, как псевдокласс :checked используется для определения стилей внешнего вида переключателя при его выборе.
Примечание. Если вы хотите использовать свойство appearance , вам следует очень внимательно его протестировать. Хотя он поддерживается в большинстве современных браузеров, его реализация сильно различается. В старых браузерах даже ключевое слово none не имеет одинакового эффекта в разных браузерах, а некоторые вообще не поддерживают его. В новейших браузерах различий меньше.
Обратите внимание,что при нажатии на радиокнопку,есть хороший,плавный эффект затухания/включения,как две кнопки меняют состояние.Кроме того,стиль и раскраска кнопки легенда и отправить настроены,чтобы иметь сильный контраст.Может быть,это и не тот вид,который вы хотели бы видеть в настоящем веб-приложении,но он определенно показывает возможности.
How do we use radio buttons in HTML forms?
Using HTML forms, we can easily take user input. The <form> tag is used to get user input by adding the form elements. Different types of form elements include text input, radio button input, submit button, text field area etc.
In this article, let us learn how to use radio buttons in HTML forms to get user input. Radio buttons are used when out of many options, just one option is required to be selected. They are also created using HTML <input> tag and the type attribute is set to radio.
Indicates the type of input control and for checkbox input control it will be set to a radio.
Used to give a name to the control which is sent to the server to be recognized and get the value.
The value that will be used if the checkbox is selected
Set to checked if you want to select it by default
Syntax
Following is the syntax to create a radio button in HTML.
Example 1
In the following example, let us learn how to use radio buttons in HTML forms −
Example 2
You can try to run the following code to learn how to work with radio buttons in HTML −
Example 3
We also use <label> tag along with the input tag. The <label> tag defines a label for several elements in the HTML.
We mainly use label for defining the value for the radio button.
Example 4
Set to checked if you want to select it by default of any of the option. We use checked attribute value to true to select a option by default. Look at the example below −
HTML Radio Button
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 <input> tag. You add type=»radio» to specify that it’s a radio button. This is because the <input> 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 <input> 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:
A user has selected a preferred color from your web form. Here is the result: