Working with radio buttons in JavaScript

Let's now work with radio buttons. They are a group of radio buttons, in which only one can be selected. For multiple radio buttons to be a group, they must have the same name attribute value:

<input type="radio" name="elem"> <input type="radio" name="elem"> <input type="radio" name="elem">

And in order to distinguish in JavaScript which button was selected, one adds value attributes with a different value to each radio button in the group:

<input type="radio" name="elem" value="1"> <input type="radio" name="elem" value="2"> <input type="radio" name="elem" value="3">

To make a radio button selected by default, it needs to set the checked attribute:

<input type="radio" name="elem" value="1" checked> <input type="radio" name="elem" value="2"> <input type="radio" name="elem" value="3">

Let's see in practice how to work with such buttons in JavaScript. Suppose we have the group of radio buttons presented above, as well as a regular button:

<input type="submit" id="button">

Let's make it so that when the button is pressed, the value of the radio button that is currently checked is displayed on the screen.

To solve the problem, it is necessary to go through all our radio buttons in a loop and determine which one is selected. To do this, you need to read the value of the property checked of each iterated radio button. If this property is equal to true, then this radio button is selected.

Let's implement the described:

let radios = document.querySelectorAll('input[type="radio"]'); let button = document.querySelector('#button'); button.addEventListener('click', function() { for (let radio of radios) { if (radio.checked) { console.log(radio.value); } } });

Given 3 radio buttons, a paragraph, and a button. On click on the button, display value of the checked radio button in the paragraph.