Radio input selected javascript

JavaScript Radio Button

Summary: in this tutorial, you will learn how to use JavaScript to check which radio button in a radio group is checked.

Introduction to the JavaScript Radio Button

Radio buttons allow you to select only one of a predefined set of mutually exclusive options. To create a radio button, you use the element with the type radio . A group of radio buttons is called a radio group.

To form a radio group, you use a common name for all the radio buttons. For example:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Radio Button title> head> body> p>Select your size: p> div> input type="radio" name="size" value="XS" id="xs"> label for="xs">XS label> div> div> input type="radio" name="size" value="S" id="s"> label for="s">S label> div> div> input type="radio" name="size" value="M" id="m"> label for="m">M label> div> div> input type="radio" name="size" value="L" id="l"> label for="l">L label> div> div> input type="radio" name="size" value="XL" id="xl"> label for="xl">XL label> div> div> input type="radio" name="size" value="XXL" id="xxl"> label for="xxl">XXL label> div> body> html>Code language: HTML, XML (xml)

In this example, all the radio buttons have the same name size but different values. Because of this, you can only select one radio button at a time.

Читайте также:  Java find files filter

To find the selected radio button, you follow these steps:

  • Select all radio buttons by using a DOM method such as querySelectorAll() method.
  • Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.

To know which radio button is checked, you use the value attribute. For example:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Radio Button title> head> body> p>Select your size: p> div> input type="radio" name="size" value="XS" id="xs"> label for="xs">XS label> div> div> input type="radio" name="size" value="S" id="s"> label for="s">S label> div> div> input type="radio" name="size" value="M" id="m"> label for="m">M label> div> div> input type="radio" name="size" value="L" id="l"> label for="l">L label> div> div> input type="radio" name="size" value="XL" id="xl"> label for="xl">XL label> div> div> input type="radio" name="size" value="XXL" id="xxl"> label for="xxl">XXL label> div> p> button id="btn">Show Selected Value button> p> p id="output"> p> script> const btn = document.querySelector('#btn'); const radioButtons = document.querySelectorAll('input[name="size"]'); btn.addEventListener("click", () => < let selectedSize; for (const radioButton of radioButtons) < if (radioButton.checked) < selectedSize = radioButton.value; break; > > // show the output: output.innerText = selectedSize ? `You selected $ ` : `You haven't selected any size`; >); script> body> html>Code language: HTML, XML (xml)

First, select the button with #btn id, output element with the #output id, and all the radio buttons with the name size :

const btn = document.querySelector('#btn'); const output = document.querySelector('#output'); const radioButtons = document.querySelectorAll('input[name="size"]'); Code language: JavaScript (javascript)

Second, register a click event listener on the button element:

btn.addEventListener('click', () => < >);Code language: PHP (php)

Third, iterate over the radio buttons and get the value of the selected radio button:

let selectedSize; for (const radioButton of radioButtons) < if (radioButton.checked) < selectedSize = radioButton.value; break; > >Code language: JavaScript (javascript)

If a radio button is checked, its checked property is true . Then, we assign the value of the selected radio button to the selectedSize variable.

Since only one radio button in a radio group can be checked at a time, the loop is terminated immediately by the break statement.

Finally, set the message for the output element:

 output.innerText = selectedSize ? `You selected $ ` : `You haven't selected any size`;Code language: JavaScript (javascript)

Radio button’s change event

When you check or uncheck a radio button, it fires the change event. To listen to the change event, you use the addEventListener() method like this:

radioButton.addEventListener('change',function(e)< >);Code language: JavaScript (javascript)

Inside the change event handler, you can access the this keyword to access the radio button. To check if the radio button is checked, you can use the checked property:

if(this.checked) < // >Code language: JavaScript (javascript)

To get the value of the checked button, you use the value property:

if(this.checked) < console.log(this.value); >Code language: JavaScript (javascript)
radioButton.addEventListener('change', function (e) < if (this.checked) < console.log(this.value); > >);Code language: JavaScript (javascript)

The following example dynamically generates a radio group and shows the selected value when a radio button is checked:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Radio Button title> head> body> p>Select your size: p> div id="group"> div> p id="output"> p> script> const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL']; // generate the radio groups const group = document.querySelector("#group"); group.innerHTML = sizes.map((size) => ` 
$ " id hljs-subst">$ ">
`
).join(' '); // add an event listener for the change event const radioButtons = document.querySelectorAll('input[name="size"]'); for(const radioButton of radioButtons)< radioButton.addEventListener('change', showSelected); > function showSelected(e) < console.log(e); if (this.checked) < document.querySelector('#output').innerText = `You selected $this.value>`
; > > script> body> html>
Code language: HTML, XML (xml)

First, define an array of strings that hold the sizes. In practice, you may get these values from a database in the back-end or from the result of an API call:

const sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL'];Code language: JavaScript (javascript)

Second, generate the radio groups from the elements of the sizes array:

const group = document.querySelector('#group'); group.innerHTML = sizes .map( (size) => ` 
$ " id hljs-subst">$ ">
`
) .join(' ');
Code language: JavaScript (javascript)

1) Select the element with id #group.

2) Generate a radio group using the map() method with template literals; each array element is corresponding to a radio button HTML.

3) Join radio button HTML strings into an HTML string using the join() method.

4) Assign the HTML to the innerHTML of the output element.

Third, select all the radio buttons with the name size and add the change event listener:

const radioButtons = document.querySelectorAll('input[name="size"]'); for (const radioButton of radioButtons) < radioButton.addEventListener('change', showSelected); >Code language: JavaScript (javascript)

Finally, define the change event handler:

function showSelected(e) < if (this.checked) < document.querySelector('#output').innerText = `You selected $this.value>`; > >Code language: JavaScript (javascript)

Summary

  • Use the element with the type radio to create a radio button.
  • Assign a name to multiple radio buttons to form a radio group. Only one radio button in the group can be selected.
  • If the radio button is selected, its checked property is true .

Источник

How to Get the Selected Radio Button Value in JavaScript

A group of radio buttons in HTML allows the user to select only one option from multiple options. In this tutorial, we will learn how to create a group of HTML radio buttons and get which one is selected using JavaScript.

Creating a Group of Radio Buttons in HTML

In HTML radio buttons are grouped by a unique name attribute. If the radio input does not have the same name attribute it will be independently selectable. In the example below only one of the following radio buttons can be selected because they all have the name attribute of day :

label for="monday">Mondaylabel> input type="radio" name="day" id="monday"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday"> 

How to Get the Selected Radio Button

Since we know a group of radio buttons is defined by a name attribute we can get them using the JavaScript document.getElementsByName() method, passing the name attribute inside the () (parenthesis) of the method.

This will return an object of elements. All we have to do is iterate through the object using a for of loop and check which one is selected using the JavaScript .checked method.

label for="monday">Mondaylabel> input type="radio" name="day" id="monday" value="1"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday" value="2" checked="checked"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday" value="3"> 
var days = document.getElementsByName('day'); for (let i of days)  if (i.checked)  console.log(i.id); > > 

The above example gets the ID of the radio button if it is checked. To get the value of a radio button use the value JavaScript property:

var days = document.getElementsByName('day'); for (let i of days)  if (i.checked)  console.log(i.value); > > 

Get the Selected Radio Button Without Iterating

It is possible to get the selected radio button without iterating by using the JavaScript document.querySelector() method.

label for="monday">Mondaylabel> input type="radio" name="day" id="monday" value="1"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday" value="2" checked="checked"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday" value="3"> 
var selected = document.querySelector('input[name="day"]:checked').id; console.log(selected); 

The above example gets the ID of the radio button that is checked. Alternatively, you could get its value like this:

var selected = document.querySelector('input[name="day"]:checked').value; console.log(selected); 

Conclusion

You now know two different ways of getting the selected radio button using JavaScript.

Источник

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