Search code examples
javascripthtmlfieldsetdisabled-input

How do I check if a form element (input or button, etc) is disabled by itself or a parent fieldset in Javascript?


According to the specs:

A form control is disabled if any of the following are true:

  • the element is a button, input, select, textarea, or form-associated custom element, and the disabled attribute is specified on this element (regardless of its value); or

  • the element is a descendant of a fieldset element whose disabled attribute is specified, and is not a descendant of that fieldset element's first legend element child, if any.

The element itself if not disabled, the disabled property is still false. How do I determine if an element is disabled by its parent?

console.log(document.querySelector("#txt").disabled)
console.log(document.querySelector("#btn").disabled)
<fieldset disabled>
  <input id="txt" />
</fieldset>

<fieldset disabled>
  <button type="button" id="btn">Button</button>
</fieldset>


Solution

  • Beside moving up the DOM tree to find a disabled fieldset, I found out CSS :disabled selector works as well:

    const txts = [1,2,3].map(q => document.querySelector("#txt" + q));
    
    for (const t of txts) {
      console.log('t.matches(:disabled):', t.matches(":disabled"));
    }
    
    function isDisabled(el) {
      if (el.disabled) { return true; }
    
      while (el = el.parentElement) {
        if (el instanceof HTMLFieldSetElement && el.disabled) { return true; }
      }
      
      return false;
    }
    
    for (const t of txts) {
      console.log('isDisabled(t):', isDisabled(t));
    }
    <fieldset disabled>
      <input id="txt1" />
    </fieldset>
    
    <fieldset>
      <input id="txt2" disabled />
    </fieldset>
    
    <fieldset>
      <input id="txt3" />
    </fieldset>