How to make input fields read-only through JavaScript?

Sometimes, we want to make input fields read-only through JavaScript.

In this article, we’ll look at how to make input fields read-only through JavaScript.

How to make input fields read-only through JavaScript?

To make input fields read-only through JavaScript, we use the setAttribute method.

For instance, we write

document.getElementById("myReadonlyInput").setAttribute("readonly", "true");

to select the input with getElementById.

Then we call setAttribute with the attribute name and value to set the readonly attribute of the input to true.

Conclusion

To make input fields read-only through JavaScript, we use the setAttribute method.