Disable and Enable an Element with JavaScript

10/03/2021

Contents

In this article, you will learn how to disable and enable an element with JavaScript.

HTMLSelectElement.disabled

To disable and enable elements like text box, radio buttons, or checkboxes, you can use the HTMLSelectElement.disabled.

const element = document.getElementById('idName');

// Disable the element
// (add the disabled HTML attribute to the element)
element.disabled = true;

// Enable the element
// (remove the disabled HTML attribute from the element)
element.disabled = false;

Demo

When you click the “Disable / Enable” button, if the input element is disabled, it will be enabled, otherwise it will be disabled.

Code

HTML

<input type="text" id="el" placeholder="Input Element">
<button type="button" id="btn">Disable/Enable</button>

JavaScript

const element = document.getElementById('el');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
  if (element.disabled) {
    // Enable the input element
    element.disabled = false;
  } else {
    // Disable the input element
    element.disabled = true;
  }
});