Categories
JavaScript Answers

How to make input fields read-only through JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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