In this tutorial we will learn How To Check Radio Button Dynamically with JavaScript. To dynamically select radio button we can use JavaScript checked property, getElementById() method and onclick event.
Table of Contents
onclick event
JavaScript onclick event attaches the click event with the JavaScript function or it triggers the click event for HTML element.
In this example onclick event is used to execute a JavaScript function which will check the radio button dynamically.
getElementById() method
JavaScript getElementById() method selects or targets the HTML element by it's id.
In this example getElementById() method is used to select the radio buttons.
checked property
JavaScript checked property either checks or unchecks the radio button or HTML checkbox or it is used to check the current state of these two input elements.
In this example checked property is used to check the radio button.
HTML Code
HTML Code is given below, in this code we have two radio buttons with two labels and two button tags with onclick event to execute two different JavaScript function.
Each function is meant to check or select it's related radio button.
<!DOCTYPE html>
<html>
<head>
<title>Check Radio Button Dynamically with JavaScript</title>
</head>
<body>
<label for="male">Male</label>
<input type="radio" value="male" id="male" name="gender">
<br>
<label for="female">Female</label>
<input type="radio" value="female" id="female" name="gender">
<br>
<button onclick="checkMale()">Select Male</button>
<button onclick="checkFemale()">Select Female</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, in this code we have two functions, each is used to check one radio button.
getElementById() method is used to select radio button while checked property will check it.
<script>
function checkMale()
{
var radio = document.getElementById('male');
radio.checked = true;
}
function checkFemale()
{
var radio = document.getElementById('female');
radio.checked = true;
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Check Radio Button in JavaScript.