In this article I will explain with an example, how to enable and disable a TextBox when RadioButton is clicked i.e. checked (selected) and unchecked (deselected) using JavaScript and jQuery.
When the RadioButton is clicked based on whether the YES RadioButton is checked (selected) or unchecked (deselected), the TextBox will be enabled or disabled.
Enable Disable TextBox based on RadioButton selection using JavaScript
The HTML Markup consists of two RadioButtons (one for Yes and other for No) and a TextBox. Each RadioButton has been assigned a JavaScript OnClick event handler.
Note: The RadioButtons must be set with exact same name attribute values in order to make them mutually exclusive.
When the RadioButton is clicked, the EnableDisableTextBox JavaScript function is executed. Inside this function, based on whether Yes RadioButton is checked (selected) or unchecked (unselected), the TextBox will be enabled or disabled.
<script type="text/javascript">
function EnableDisableTextBox() {
var chkYes = document.getElementById("chkYes");
var txtPassportNumber = document.getElementById("txtPassportNumber");
txtPassportNumber.disabled = chkYes.checked ? false : true;
if (!txtPassportNumber.disabled) {
txtPassportNumber.focus();
}
}
</script>
<span>Do you have Passport?</span>
<label for="chkYes">
<input type="radio" id="chkYes" name="chkPassPort" onclick="EnableDisableTextBox()" />
Yes
</label>
<label for="chkNo">
<input type="radio" id="chkNo" name="chkPassPort" onclick="EnableDisableTextBox()" />
No
</label>
<hr />
Passport Number:
<input type="text" id="txtPassportNumber" disabled="disabled" />
Enable Disable TextBox based on RadioButton selection using jQuery
The HTML Markup consists of two RadioButtons (one for Yes and other for No) and a TextBox. Each RadioButton has been assigned a jQuery Click event handler.
Note: The RadioButtons must be set with exact same name attribute values in order to make them mutually exclusive.
When the RadioButton is clicked, based on Yes RadioButton is checked (selected) or unchecked (unselected), the TextBox will be enabled or disabled.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("input[name='chkPassPort']").click(function () {
if ($("#chkYes").is(":checked")) {
$("#txtPassportNumber").removeAttr("disabled");
$("#txtPassportNumber").focus();
} else {
$("#txtPassportNumber").attr("disabled", "disabled");
}
});
});
</script>
<span>Do you have Passport?</span>
<label for="chkYes">
<input type="radio" id="chkYes" name="chkPassPort" />
Yes
</label>
<label for="chkNo">
<input type="radio" id="chkNo" name="chkPassPort" />
No
</label>
<hr />
Passport Number:
<input type="text" id="txtPassportNumber" disabled="disabled" />
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads