How to Onclick Disable Input Field JavaScript

Sometimes, we need to prevent users to fill the input fields. To do that we have to disable input fields using JavaScript or jQuery. In this article, we are going to learn this technique in JavaScript.

Disable Input Fields Using 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 just 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

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 the disabled property of the input field properly.

Happy Scripting 🙂

Leave a Reply

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