We can use JavaScript to get the radio button value using the querySelector method along with the value property.
document.querySelector('input[name="radio1"]:checked').value;
Where radio1 in the code above would be the name attribute that all of the radio buttons share.
Let’s see an example of this below.
Lets say we have the following HTML:
Select your favorite mode of transportation:
In this example, the radio button Train will be set to checked to start. We can use our code from above to get this value using JavaScript.
Here is the JavaScript code we will need:
var radioButtonValue = document.querySelector('input[name="transport"]:checked').value;
Try it out below by selecting a radio button and then clicking the button below to see what radio button is checked:
Code Output:
Select your favorite mode of transportation:
Full Code:
Select your favorite mode of transportation:
Check which radio button is selected with JavaScript
Using JavaScript to Set the Value of a Radio Button
We can also use JavaScript to set the value of a radio button. We simply need to change the checked property of the radio button to true. Here is how we can do this:
document.getElementById("airplane").checked = true;
Let’s see this result in a similar example to the one above.
Code Output:
Select your favorite mode of transportation:
Full Code:
Select your favorite mode of transportation:
Set the radio button Airplane to checked