In this article, we will disable a specific radio button using JavaScript. Disabling specific radio button options using JavaScript involves targeting the specific option and then set its disabled property to true. This can be done by selecting the radio button option and modifying its disabled property accordingly.
- Disabling a radio button option prevents the user from selecting it, but the option remains visible.
- Disabled radio button options are not included in form submissions, so their values are not sent to the server.
Approach 1: Using setAttribute() and removeAttribute() Methods
The setAttribute method adds the disabled attribute to a specific radio button option and the removeAttribute() method remove it. This approach allow to dynamically enable or disable specific options based on certain conditions.
<!DOCTYPE html>
<html>
<head>
<title>
How to Disable Specific Readio
Button Option using JavaScript?
</title>
</head>
<body>
<p>Select Subject</p>
<input type="radio" id="html"
name="radioGroup" value="html">
<label for="html">HTML</label>
<br>
<input type="radio" id="css"
name="radioGroup" value="css">
<label for="css">CSS</label>
<br>
<input type="radio" id="js"
name="radioGroup" value="javascript">
<label for="js">JavaScript</label>
<br><br>
<button onclick="disableOption()">
Disable JavaScript
</button>
<script>
function disableOption() {
let option = document.getElementById("js");
option.setAttribute("disabled", "disabled");
}
</script>
</body>
</html>
Output:
Approach 2: Using the disabled Property
You can also directly manipulate the disabled property of the specific radio button option to enable or disable it. This approach is very basic and does not require setting or removing attributes.
<!DOCTYPE html>
<html>
<head>
<title>
How to Disable Specific Readio
Button Option using JavaScript?
</title>
</head>
<body>
<p>Select Subject</p>
<input type="radio" id="html"
name="radioGroup" value="html">
<label for="html">HTML</label>
<br>
<input type="radio" id="css"
name="radioGroup" value="css">
<label for="css">CSS</label>
<br>
<input type="radio" id="js"
name="radioGroup" value="javascript">
<label for="js">JavaScript</label>
<br><br>
<button onclick="disableOption()">
Disable JavaScript
</button>
<script>
function disableOption() {
let option = document.getElementById("js");
option.disabled = true;
}
</script>
</body>
</html>
Output: