Radio checked html javascript

How to check whether a radio button is selected with JavaScript?

In the HTML, the radio buttons allow developers to create multiple options for a choice. Users can select any option, and we can get its value and know which option users have selected from the multiple options.

So, it is important to check which radio button the user selects to know their choice from multiple options. Let’s understand it via real-life examples. When you fill out any form and ask to choose a gender, you can see they give you three options, and you can select only one.

In this tutorial, we will learn two approaches to checking whether a radio button is selected using JavaScript.

Using the checked property of the radio button

We can access the radio element in JavaScript using various methods. After that, we can use its checked property to check whether the selected radio button is checked. If the value of the checked property is true, it means the radio button is selected; otherwise, it’s not selected.

Читайте также:  Mb regex encoding php

Syntax

Users can follow the syntax below to check whether the radio button is selected using the checked property of the radio element.

 Male  

In the above syntax, we have accessed the radio button using its id and used the checked attribute to check whether the radio button is selected in the if-statement.

Example

In the example below, we have created three radio buttons containing different values, such as male, female, and others. In JavaScript, we have accessed each radio button by its id and checked the value of every radio button’s ‘checked’ property.

When the user selects any radio button and clicks on the button, they see a message showing the value of the selected radio button.

  

Using the checked property of the radio button to check whether a radio button is selected.

Male
Female
Other

Example

The example below is almost the same as the one above, but the difference is that we are accessing all radio buttons using their name at once. The getElementByName() method returns all radio elements with the name radio.

After that, we used the for-of loop to iterate through the array of radio buttons and check for every radio button using the ‘checked’ property whether the radio button is selected.

  

Using the checked property of the radio button to check whether a radio button is selected

10
20
30

Use the querySelector() method to check whether a radio button is selected

Programmers can use JavaScript’s querySelector() method to select any HTML element. Here, we have used the querySelector() method to select only the checked radio button. If no radio button is selected, it returns a null value.

Syntax

Users can follow the syntax below to use the querySelector() method to check whether the radio button is selected.

var selected = document.querySelector('input[name="year"]:checked');

In the above syntax, ‘year’ is the name of the group of radio buttons, and it returns any radio button which belongs to the ‘year’ group and is checked.

Example

In the example below, we created three radio buttons providing three different choices to the users. When users click on the Check selected year button, it invokes the getSelectedRadio() function, which uses the querySelector() method to select the radio button with the name ‘year’ and is checked from the DOM.

Users can click the button without selecting any radio button and observe the output.

  

Using the querySelector() method to check whether a radio button is selected.

1999
2021
2001

Users learned two different methods to get the checked radio buttons using JavaScript. The best way to do this is to use the querySelector() method, as we need to write only a single line of code.

Источник

Radio checked html javascript

Last updated: Jan 11, 2023
Reading time · 3 min

banner

# Set a Radio button to Checked/Unchecked using JavaScript

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio.checked = true .

When set to true , the radio button becomes checked and all other radio buttons with the same name attribute become unchecked.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> input type="radio" id="yes" name="choose" value="yes" /> label for="yes">Yeslabel> input type="radio" id="no" name="choose" value="no" /> label for="no">Nolabel> input type="radio" id="maybe" name="choose" value="maybe" /> label for="maybe">Maybelabel> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const yesBtn = document.getElementById('yes'); // ✅ Set the radio button to checked yesBtn.checked = true; // ✅ Set the radio button to unchecked // yesBtn.checked = false;

We selected the radio button using the document.getElementById method.

We then set the element’s checked property to true .

# Setting a radio button to unchecked

If you need to uncheck a specific radio button, set its checked property to false .

Copied!
const yesBtn = document.getElementById('yes'); // ✅ Set radio button to checked yesBtn.checked = true; // ✅ Set radio button to unchecked yesBtn.checked = false;

Note that checking a radio button automatically unchecks all other radio buttons with the same name attribute.

Copied!
const yesBtn = document.getElementById('yes'); yesBtn.checked = true; const noBtn = document.getElementById('no'); noBtn.checked = true;

We first checked the yes radio button, but when we checked the no button, the yes button got automatically unchecked.

# Setting a radio button to be checked by default

You can set a radio button to be checked by default by setting the checked property directly on the input field.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> input type="radio" checked id="yes" name="choose" value="yes" /> label for="yes">Yeslabel> input type="radio" id="no" name="choose" value="no" /> label for="no">Nolabel> input type="radio" id="maybe" name="choose" value="maybe" /> label for="maybe">Maybelabel> script src="index.js"> script> body> html>

Note that if you don’t assign the same name attribute value to all of the radio input fields in the group, you will be able to check multiple radio buttons at the same time.

If this is the behavior your use case requires, you should use a checkbox instead of a radio button.

You might see examples online that use the setAttribute and removeAttribute methods to check and uncheck a radio button.

Copied!
const yesBtn = document.getElementById('yes'); // ✅ Check the radio button yesBtn.setAttribute('checked', ''); // ✅ Uncheck the radio button // yesBtn.removeAttribute('checked');

This is also perfectly fine, however, there are a couple of things to keep in mind when using the setAttribute method.

The method takes the following 2 parameters:

  1. name — the name of the attribute to be set.
  2. value — the value to assign to the attribute.

If the attribute already exists on the element, the value is updated, otherwise, a new attribute is added with the specified name and value.

When setting the value of a boolean attribute, such as checked , we can specify any value for the attribute and it will work.

If a boolean attribute, such as checked , is not present, the value of the attribute is considered to be false .

When setting the checked attribute, we pass an empty string as the value for the attribute because it’s a best practice to set boolean attributes without a value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

JavaScript урок12. Объектная модель документа (продолжение): идентификация в javascript checkbox и radio

егэ разбор егэ разбор pascal уроки c уроки python уроки c++ уроки vb уроки lazarus уроки php уроки html уроки css уроки javascript уроки jquery и ajax уроки prolog уроки flash уроки

На уроке рассматриваются способы доступа в javascript к checkbox (флажкам) и radio (радио-кнопкам или переключателям). Разбирается принцип работы со свойством checked для осуществления проверки radio и checkbox

Объект javascript checkbox

form name="f1"> input type="checkbox" name="yourName" id="ch1"> Да /form>

Элемент checkbox идентифицируется:

document.getElementById('ch1').checked=true;

Пример: По щелчку на элементе флажок (checkbox) выводить диалоговое окно с сообщением для подтверждения: «Номер люкс очень дорогой. Вы уверены?». Скрипт описать в качестве значения атрибута.

input type="checkbox" name="checkbox1" value="Номер Люкс" onсlick=" confirm('Номер люкс очень дорогой. Вы уверены?')">Номер люкс

Свойство checked

Пример: По загрузке страницы устанавливать флажок (checkbox) отмеченным

1 способ (через name ):
В скрипте:

function check(){ document.f1.ch1.checked=true; }
body onload="check()"> form name="f1"> input type="checkbox" name="ch1">пункт1br> input type="checkbox" name="ch2">пункт2br> /form> …

2 способ (через id ):
В скрипте:

function check(){ ch1.checked=true; }
body onload="check()"> input type="checkbox" id="ch1">пункт1br> input type="checkbox" id="ch2">пункт2br>

checkbox javascript

Задание js12_1. Создать страницу проверки знаний учащегося с одним вопросом и тремя ответами на вопрос: два из них правильные и один неправильный. Осуществить проверку правильности отмеченных при помощи элементов формы checkbox ответов. Функцию проверки запускать по щелчку кнопки

Объект переключатель в javascript — radio и свойство checked

Элемент javascript radio предназначен для выбора только одного единственного варианта из нескольких.

Для того, чтобы несколько переключателей работали сгруппировано, т.е. чтобы при выборе одного radio все остальные бы отключались, необходимо для всех radio установить одинаковое значение атрибута name

Рассмотрим пример использования радиокнопок:
html-код:

body> form name="f1"> Ваш пол:br> input type="radio" name="r1" id="id1"br> input type="radio" name="r1" id="id2"br> input type="button" onclick="fanc()"> /form> /body>

Группа радиокнопок (radio) идентифицируется в скрипте следующим образом:
Скрипт:

function fanc(){ document.getElementById("id1").checked=true; // 1-й способ document.f1.r1[0].checked=true; // 2-й способ document.f1['r1'][0].checked=true; // 3-й способ }

Первый способ является наиболее предпочтительным.

Рассмотрим пример использования в javascript radio с checked свойством:

1 способ:
Скрипт:

function fanc(){ idr1.checked=true; }
input type="radio" name="r1" id="idr1">пункт1br> input type="radio" name="r1" id="idr2">пункт1br> input type="button" onClick ="fanc()" value="отметить">

2 способ:
Скрипт:

function fanc(){ document.f1.r1[0].checked=true; }
form name="f1"> input type="radio" name="r1">пункт1br> input type="radio" name="r1">пункт1br> input type="button" onClick ="fanc()" value="отметить"> /form>

radio в javascript

Задание js12_2.
Создать страницу проверки знаний учащегося с вопросом: «Какой заряд у электрона?» и двумя ответами: «положительный» (неправильный) и «отрицательный» (правильный). Осуществить проверку правильности отмеченного при помощи элемента формы radio ответа. Функцию проверки запускать по щелчку кнопки

Источник

Оцените статью