This is a short guide on how to disable input text fields using JavaScript. In this tutorial, I will show you how to accomplish this using both regular JavaScript and the JQuery library.
Choose your poison!
Let’s take the following text field as an example:
<!-- An example text input field --> <input type="text" id="name" value="Wayne">
I have given the input field above the ID “name“. The ID attribute is important as it allows us give each input field a unique ID. This allows us to pinpoint the exact element that we want to disable.
Disabling the input field with regular JavaScript.
Let’s start off by using plain old JavaScript:
//Disabling a text input field with regular JavaScript. document.getElementById("name").disabled = true;
In the code snippet above, we referenced the input field by its ID using the getElementById() method. We then set its disabled attribute to true.
In Chrome, this resulted in the following:
As you can see, the text field has been disabled and “grayed out.”
If you open up your browser’s developer tools and look at the DOM, you will see that the disabled attribute has been added to the field in question:
<!--What it looks like in the DOM--> <input type="text" id="name" value="Wayne" disabled="disabled">
It’s that simple!
Disabling the input field using JQuery.
If you’re already using the JQuery library, then you might want to use the following example:
//Disabling a text input field using JQuery. $('#name').attr('disabled', true);
In the code snippet above, we used JQuery’s .attr() method to set the disabled attribute to true. This does the exact same thing as the code that we used in our vanilla JavaScript example. The only difference is that it is a little shorter.
Hopefully, you found this guide useful!