Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  139] [ 1]  / answers: 1 / hits: 17904  / 10 Years ago, fri, may 16, 2014, 12:00:00

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


More From » dom

 Answers
10

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


[#70975] Thursday, May 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byrondonavanc

Total Points: 675
Total Questions: 107
Total Answers: 105

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
byrondonavanc questions
;