How to Disable TextBox/Input Field Onclick Using JavaScript

Sometimes, we need to disable textbox or input fields using JavaScript. To enable/disable textbox in JavaScript, we can use DOM properties.

Disable TextBox / Input Field in JavaScript

It is quite easy to disable an input field using JavaScript. Here, we are going to disable an input field onclick event of a button using simple js. However, you can set it to any event like onhover, ondoubleclick, onchange, etc. It may depend on your webpage or form user flow.

Example 1

<!DOCTYPE html>
<html>
<body>
<input type="text" id="my_field" name="Name" placeholder="Enter Your Name"/>
<br>
<button onclick="disable()">Disable</button>
<script>
  function disable(){
	document.getElementById("my_field").disabled = "true";
  }
</script>
</body>
</html>

As we can see in the above example, we have to select the input field we want to disable first. After that, we have to set its disabled property to true.

We can also remove the disabled property of the input field using JavaScript. In the below example, we will learn how to remove disabled property and unlock the input field to the user.

Read Also: Change Text Onclick JavaScript

Enable and Disable TextBox / Input Field in JavaScript

Example 2

<!DOCTYPE html>
<html>
<body>
<input type="text" id="my_field" name="Name" placeholder="Enter Your Name"/>
<br>
<button onclick="disable()">Disable</button>
<button onclick="enable()">enable</button>
<script>
  function disable(){
	document.getElementById("my_field").disabled = "true";
  }
  function enable(){
	document.getElementById("my_field").disabled = "";
  }
</script>
</body>
</html>

In the above example, we created another button to enable the input field. To enable we set the disabled property of the input field to the “”(empty) value which will enable the input field.

Conclusion

I hope you know how to enable and disable textbox or input field using JavaScript.

Happy Scripting πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *