Disable and Enable an Element with JavaScript

Web Design & Web Development

In this article, I will introduce 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;
Sponsored links

Demo

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

Sponsored links

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;
  }
});