JavaScript program to get the selected radio button value

JavaScript program to get the selected radio button value:

In this post, we will learn how to get the selected radio button’s value from a couple of radio buttons using JavaScript. We will create one simple HTML file with two radio buttons. One button will be there below the buttons. If the user clicks on the button, it will show which button is selected with an alert.

HTML/JavaScript program:

Below is the complete program: Create one index.html file and copy-paste the below code. Open the file in any web-browser to view the changes.

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Radio Button Example</title>
		<script type="text/javascript">
			function buttonClickListener(){
				if(document.getElementById('radioFirst').checked){
					alert("You have selected the first radio button.");
        }
				else if(document.getElementById('radioSecond').checked){
					alert("You have selected the second radio button.");
        }
        else{
          alert("Please select atleast one radio button.")
        }
			}
		</script>
	</head>
<body style="text-align: center;">
	<h1>Select a radio button and click on 'Find Selected'</h1>
	<input type="radio" name='radioexample' id="radioFirst" value="First">First</input>
	<input type="radio" name='radioexample' id="radioSecond" value="Second">Second</input>
	<br><br>
	<input type="button" value="Find Selected" onClick="buttonClickListener()"/>
</body>

</html>

Here,

  • This is for HTML file. It also includes javascript code. The code inside script tags is JavaScript
  • We have added two radio buttons in the body. You can select only one of these buttons because both have the same name. One button is added below these radio-buttons. On clicking this button, buttonClickListener method gets called.
  • buttonClickListener method is defined in the JavaScript code. It checks which radio button is checked and shows one alert message.

It will look as like below: javascript get selected radio button

You can click on any of these radio buttons and click on the button to see the alert.

You might also like: