Using the disabled Attribute

Question: How to set and test if an input element is disabled?

Results:

Use disabled or disabled="disabled" to set in markup. When setting via scripting use inputObj.disabled=true and inputObj.disabled=false via boolean values; inputObj.disabled="disabled" and inputObject.disabled="" via string values; or inputObj.setAttribute("disabled", "disabled") and inputObj.removeAttribute("disabled") to disable and enable, respectively. When testing for the disabled attribute on an input element, use inputObject.disabled for consistent results between browers.

More details: Once again I was bitten by the manner in which the difference browsers report the value of the disabled attribute. When writing JavaScript I generally use the object.getAttribute("attributeName") syntax to get an attribute value. However, this will return very inconsistent results for the disabled attribute. What makes it even worse, is there is more than one way to specify the disabled attribute on an input element. In HTML 4.01 you should just add the keyword disabled. In XHTML 1.1 you must use disabled="disabled". You can also use this in HTML 4.01. Using inputObject.disabled to retrieve a disabled value set in markup will consistently return a boolean result.

Below are several input type="text" elements, some of which have been disabled in the markup and some via script. The label for the text box indicates how the disabled attribute was set. The scripted text boxes have the disabled attribute set on page load via the method indicated in the label. If you have scripting turned off, the 6 scripted textboxes below will all be enabled.

labelInputMarkup
<input id="none" type="text" >
<input id="keyword" type="text" disabled> Not valid in XHTML 1.1
<input id="true" type="text" disabled="disabled">
Note that setAttribute("disabled","") only works to enable the textbox in IE6/7

Testing Results HTML 4.01 strict

Firefox 3IE8 (as IE8)IE6/7Safari 4(WinXP)
getAttribute("disabled");inputObject.disabledgetAttribute("disabled");inputObject.disabledgetAttribute("disabled");inputObject.disabledgetAttribute("disabled");inputObject.disabled
enablednullfalse""falsefalsefalsenullfalse
disabled keyword""true"disabled"truetruetrue""true
disabled="disabled""disabled"true"disabled"truetruetrue"disabled"true
setAttribute("disabled","disabled")"disabled"true"disabled"truetruetrue"disabled"true
setAttribute("disabled","")""true"disabled"truefalsefalse""true
inputObject.disabled=true""true"disabled"truetruetrue""true
inputObject.disabled=falsenullfalse""falsefalsefalsenullfalse
inputObject.disabled="disabled"""true"disabled"truetruetrue""true
inputObject.disabled=""nullfalse""falsefalsefalsenullfalse

simple disabled attribute test file (few comments or text)

Posted on June 23, 2009 by Becky Gibson