Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM 'disabled' property in javascript

Tags:

javascript

dom

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).

like image 664
Legion Avatar asked Nov 27 '22 13:11

Legion


2 Answers

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().

like image 101
canon Avatar answered Dec 04 '22 11:12

canon


The .disabled property of DOM elements is a boolean value and should get booleans assigned.

The disabled HTML attribute, like in markup or setAttribute(), is a "boolean html attribute" which means it can take the values empty, disabled or be omitted. See also HTML - Why boolean attributes do not have boolean value? and Correct value for disabled attribute.

like image 21
Bergi Avatar answered Dec 04 '22 10:12

Bergi