DOM 'disabled' property in javascript
dom, javascript
Solution
The following input elements are all disabled:
<input disabled />
<input disabled="" />
<input disabled="disabled" />
<input disabled="true" />
<input disabled="false" /> <!-- still disabled! -->
If a boolean attribute is present, it's on; otherwise, it's off. The value doesn't mean anything.
However, when dealing with these elements through javascript, you should make use of the corresponding property, i.e.:
myInput.disabled = true; // adds the attribute and disables control
myInput.disabled = false; // removes the attribute and enables control
The property will update the attribute for you. This is true of all boolean attribute / property pairs, i.e.: `readonly`, `checked`, `selected`, etc.
Confusion may stem from the fact that `setAttribute()` asks for both a name and value and emits markup in a `key="value"` format -even when you don't want a value. When adding a custom boolean attribute, I simply set the attribute without a value (sample):
input.setAttributeNode(document.createAttribute("data-custom"));
console.log(input); // <input data-custom>
See `document.createAttribute()` and `Element.setAttributeNode()`.
Problem
I can't find a definitive answer to how to use the disabled property to disable form elements in javascript. Some places say it's a simple boolean. Other's say to set it to the string value 'disabled' to disable, empty string '' to enable. Or there's adding and removing the disabled attribute, usually in combination with a string value. So which is the proper way to do it cross browser? (no jQuery). How did something as simple as an enable flag get so butchered? -- edit -- Sorry, I should have mentioned I'm developing for IE8 (not by choice).