Press "Enter" to skip to content

Enable Disable Textbox Using JavaScript Example

In this tutorial, you will learn how to enable/disable textbox using JavaScript on the radio button click.

Enable/Disable TextBox Using JavaScript on Radio Button Click Example

In the below example, it will create three radio buttons and three textboxes and will enable or disable on the radio button click using JavaScript.

 

<!DOCTYPE html>
<head>
<title>
Click on Radio Button To Enable Fields
</title>
<style>
:enabled {
border: 4px solid #ff0000;
padding: 5px 5px 5px 15px;
}
:disabled {
border: 2px solid #cccccc;
}
</style>
<script>
//<![CDATA[
window.onload=function() {
// disable all the input textboxes first
document.forms[0].elements["intext"].disabled=true;
document.forms[0].elements["intext2"].disabled=true;
document.forms[0].elements["intext3"].disabled=true;
// on click event handler
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
// check which radio button clicked then enable or disable accordingly
switch(this.value) {
case "one" :
document.forms[0].elements["intext"].disabled=false;
document.forms[0].elements["intext2"].disabled=true;
document.forms[0].elements["intext3"].disabled=true;
break;
case "two" :
document.forms[0].elements["intext2"].disabled=false;
document.forms[0].elements["intext"].disabled=true;
document.forms[0].elements["intext3"].disabled=true;
break;
case "three" :
document.forms[0].elements["intext3"].disabled=false;
document.forms[0].elements["intext"].disabled=true;
document.forms[0].elements["intext2"].disabled=true;
break;
}
}
//--><!]]>
</script>
</head>
<body>
<form id="picker">
Group 1: 
<input type="radio" name="group1" value="one" />
<br />
Group 2: 
<input type="radio" name="group1" value="two" />
<br />
Group 3: 
<input type="radio" name="group1" value="three" />
<br />
<br />
<input type="text" id="intext" />
<input type="text" id="intext2"  />
<input type="text" id="intext3"  />
</form>
</body>
</html>

Output

You can see the featured image of this article for the output of the above program.