How to Add and Remove Readonly Attribute in Javascript

In this tutorial, you will learn how to add and remove readonly attribute in javascript. The readonly attribute makes your input field completely immutable.  However, you can still change the text in the input field with the help of javascript.

There are specific methods in the javascript to add and remove attributes.  The setAttribute() method is used whenever you want to add an attribute to an element and the removeAttribute() method is used whenever you want to remove an attribute from an element.

In the following example, we have 2 buttons and one input field.  One button is to add readonly attribute to the input field and another one is to remove it on click. Please have a look over the code example and steps given below.

HTML & CSS

  • We have 4 elements in the HTML file and that includes 1 div element, 2 button elements, and 1 input element.
  • The div element is just a wrapper for the rest of the elements.
  • The inner text for the first button element is “Add” and for the second button element, it is “Remove”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  
  <div>
    <button id="add">Add</button>
    <button id="remove">Remove</button>
    <input type="text">
  </div>
  <script src="script.js"></script>
</body>
</html>
div {
    text-align: center;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

input {
    display: block;
    padding: 10px 20px;
    margin: 10px auto;
}

Javascript

  • We have selected both the button elements and the input element using document.querySelector() and stored them in btnAdd, btnRemove, and input variables respectively.
  • We have attached the click event listener to both the button elements.
  • In the event handler function of add button, we are calling the setAttribute() method of the input element to add readonly attribute.
  • In the event handler function of the remove button, we are calling the removeAttribute() method of the input element to remove readonly attribute.
let btnAdd = document.querySelector('#add');
let btnRemove = document.querySelector('#remove');
let input = document.querySelector('input');

btnAdd.addEventListener('click', () => {
    input.setAttribute('readonly', true);
});

btnRemove.addEventListener('click', () => {
    input.removeAttribute('readonly');
});