Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 22, 2023 › #Button #HowTo

How to get value of selected radio button using JavaScript

Today, I'm going to show you how to get the value of a selected radio button using JavaScript.

This is an incredibly useful tool when creating web forms as it allows you to quickly and easily determine which option has been chosen by the user. So let's dive right in!

The first step is to create a form with at least two radio buttons that use unique values for each one.

To do this, simply add type="radio" and name="gender" attributes within your HTML input tags like so:

<input type="radio" name="gender" value="male"> Male <br>  	    		 
<input type="radio" name="gender" value="female">Female <br> 

Next up, we need some JavaScript code that will allow us to capture the selected radio button's value when it changes or is clicked on by the users.

The easiest way to do this is using an event listener such as onclick. Here is what our code should look like:

<script>
  document.getElementById("my-btn").addEventListener("click", function() { 
    let genderValue = document.querySelector('input[name="gender"]:checked').value;      
    alert(`You are ${genderValue}`);
  }); 
</script>

Now, all we have to do is run our script and check if everything works correctly! Hopefully, this tutorial helps show how easy it is to get the value of a selected radio button via JavaScript.

save
listen
AI Answer
Write Your Answer
loading
back
View All