Enabling / Disabling Form Elements using JavaScript

The Enabling/Disabling element takes two values that is true or false, if we set to true then we can enable the element that means the user can edit the elements which user wants to do in the form or text box or else if it is set to be false then the element is disable that means you can’t do any changes or editing work in the particular form or in text box.

Syntax

document.getElementById("element_id").disabled=true/false

Enabling / Disabling Form Elements Example

<!DOCTYPE html>
<head>
<script>
function Degree()
{
if (document.getElementById('pupil').disable == true)
  {
	document.getElementById('Name').removeAttribute('disabled'); document.getElementById('Relation').removeAttribute('disabled');
 }
else
  {
   	document.getElementById('Name').removeAttribute('disabled','disabled');
 	document.getElementById('Relation').removeAttribute('disabled','disabled');
  }
}
</script>
</head>
<body>
<h2> Admission Form</h2>
<form id="orderform" >

Name: <input type= "Text"><br>
DOB:  <input type= "Text"><br>
Does this pupil belong to our school: <input type= "checkbox"  id= "pupil" name="pupil"  value="yes" onclick="javascript:Degree();">Yes
<input type= "checkbox"> No<br>

Name of the pupil: <input type="text" id="Name" name="Name" disabled/>
Relation with the Pupil:<input type="text" id="Relation" name="Relation" disabled />

</form>
</body>
</html>
  • In this program we have shown that how the enabling and disabling elements works
  • We have used Yes and No button in the form. When we click on Yes button the following text box will be available to user to write further details in the form.
  • if (document.getElementById(‘pupil’).checked == true) is used to call a element by using id and disabled is set to be true to make elements enable.
  • onclick=”javascript:Degree();” this event works when we click on yes and it makes the following text box available to fill the information.

Enabling / Disabling Form Elements Demo

  • Save the file as enabling_disabling.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.

When the execution process is completed successfully we will get the following output:

Enabling / Disabling Form Elements

Now check the “Yes” box and you would that the fields below this box are enabled as shown in the screen below:
Enabling / Disabling Form Elements

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*