Javascript check if any radio checked

Checking a Radio Button in JavaScript

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .

In this post you’ll learn a few ways to check a selected radio input ( ) and explore a few different options and approaches.

If you think using checked is the only answer — it’s not!

We’ll answer questions such as “How can I check a specific radio button?” and “How do I check a radio button based off a value?”. Let’s go!

Here’s the markup we’ll use to demonstrate setting a radio button’s value, notice how we’ll begin selecting a default value with HTML via the checked attribute — that’s the first way to set a checked radio (and it works without JavaScript enabled too 😉):

 name="demo"> Mario  type="radio" value="mario" name="characters" checked />  Luigi  type="radio" value="luigi" name="characters" />  Toad  type="radio" value="toad" name="characters" />   

So now let’s get a reference to our form as well as the group of radio controls:

const form = document.forms.demo; const radios = form.elements.characters; 

Here we’re using the new HTMLFormElement.elements property which allows us to access the name=»characters» attribute on the input.

Note: All radio buttons that you’d like in the same group need to have the same name=»value» attribute for them to “link together”.

So, how do we set the value and check the radio button? Let’s first explore setting the value pragmatically, through setting the value we want via a string, and secondly we’ll look at querying the specific radio to be checked and manually checking it.

Using the RadioNodeList.value property

If we log out the resulting value of const radios we’ll see something interesting:

// ▶ RadioNodeList(3) [input, input, input, value: "mario"] console.log(radios); 

Well, that certainly looks interesting, a RadioNodeList? Nice!

The RadioNodeList interface represents a collection of radio elements in a or a element.

You’ll also note that this is an Array-like object, which means we can iterate it as well as access the .value property — on the same object! We’re really only interested in this value property which is the simplest way to set a radio button as checked if we have the value that we want to set:

const radios = form.elements.characters; radios.value = 'luigi'; 

Here we’ll set ‘luigi’ as the RadioNodeList.value (the group of radios) which will mark the radio thats value matches as “checked” and we’ll see it update in the browser!

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Observables and Async Pipe
  • Identity Checking and Performance
  • Web Components syntax
  • and Observable Composition
  • Advanced Rendering Patterns
  • Setters and Getters for Styles and Class Bindings

That went smoothly, check your email.

To demonstrate this technique more visually, we could combine an IIFE recursively use a setTimeout to update the radios in our markup every 1 second, with a random value from our values array!

👻 There’s something strange, that I just found out… using radios.value will set the value, however it won’t fire any “change” event listeners on that element. Who you gonna call?

const form = document.forms.demo; const radios = form.elements.characters; const values = ['mario', 'luigi', 'toad']; (function selectRandomValue()  radios.value = values[Math.floor(Math.random() * values.length)]; setTimeout(selectRandomValue, 1000); >)(); 

Try the live StackBlitz demo which demonstrates the recursive value randomiser:

So far we’ve used this radios.value property, which gets us pretty much where we need to. However, it involves us knowing the value we want to set upfront, it might be that we want to somehow get a reference to a radio button and then set that radio button to checked.

Using the “checked” property

Now let’s look at the DOM Node level method of checking a radio button — the checked property. It is as simple as setting it to true !

First though, we need a reference to the DOM Node we’d like to set to checked . As our radios variable returns a RadioNodeList , we could access its members like an array:

const form = document.forms.demo; const radios = form.elements.characters; const radioToUpdate = radios[0]; radioToUpdate.checked = true; 

We could use radios[1] or radios[2] to get further values, and yes a NodeList also has zero-based index system like an array.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Observables and Async Pipe
  • Identity Checking and Performance
  • Web Components syntax
  • and Observable Composition
  • Advanced Rendering Patterns
  • Setters and Getters for Styles and Class Bindings

That went smoothly, check your email.

It’s worth mentioning that we can also randomly select a chosen index from our RadioNodeList and set that radio button’s property to checked :

const form = document.forms.demo; const radios = form.elements.characters; (function selectRandomValue()  radios[Math.floor(Math.random() * radios.length)].checked = true; currentValue.innerText = radios.value; setTimeout(selectRandomValue, 1000); >)(); 

Here’s another StackBlitz example that also live updates each 1 second:

Summary

So many options! Which is the best one to choose? If you have a reference to that radio button, you might as well go ahead and use the checked property.

If you’ve got a few values that also match some of the radio values, you can use the radios.value = ‘luigi’ syntax that we explored — this is also really nice as you don’t need to deal with the DOM Node directly, we’re dealing with the RadioNodeList wrapper that is holding the radios!

😎 Next up learn how to Get the Value of Checked Radio Buttons to complete your Input Radio knowledge!

Browser support

Check the browser support for:

tl:dr; the browser support in evergreen browsers is super.

The .elements has no Internet Explorer support but has Edge support.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

  • Observables and Async Pipe
  • Identity Checking and Performance
  • Web Components syntax
  • and Observable Composition
  • Advanced Rendering Patterns
  • Setters and Getters for Styles and Class Bindings

That went smoothly, check your email.

I hope you enjoyed the post, and if you’d love to learn more please check out my JavaScript courses, where you’ll learn everything you need to know to be extremely good and proficient at the language, DOM and much more advanced practices. Enjoy and thanks for reading!

Learn JavaScript the right way.

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students .

Источник

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.

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.

Источник

How to check if radio button is checked or not using JavaScript?

There are few different ways we can check that based on you have a single radio button or multiple.

Input Radio checked Property

The checked property sets or returns the checked state of a radio button.

This property reflects the HTML checked attribute.

It is supported in all major browsers.

Syntax

 radioId.checked = true //or radioId.checked = false 

Where true| or false specifies whether a radio button should be checked or not. true means the radio button is checked and false means the radio button is not checked.

Examples

Find out if a radio button is checked or not:

 var x = document .getElementById("testRadioButton") .checked; 

What to do when you have more than one radio buttons?

Use a for loop to go through each one of them and find out which one is checked:

 //JS function myFunction() < var coffee = document.forms[0]; var txt = ""; var i; for (i = 0; i < coffee.length; i++) < if (coffee[i].checked) < txt = txt + coffee[i].value + " "; >> document.getElementById("order").value = "You ordered a coffee with: " + txt; >

Use for loop example for multiple radio buttons

 // JS const btn = document.querySelector("#btn"); btn.onclick = function () < const selections = document.querySelectorAll('input[name="coffee"]'); let userSelection; for (const selection of selections) < if (selection.checked) < userSelection = selection.value; break; >> console.log(userSelection); >; 

Источник

Читайте также:  Иконки css как подключить
Оцените статью