Re enabling input elements with javascript

Posted: Friday 14 June 2013

Throughout my experience with HTML and javascript, re enabling input elements with javascript is an issue that has really caught me off guard, and one of the main reasons as to why I put off using disabled inputs.
Basically, every single time I attempt to create a script that will disable and enable an input button (as in making a button unclickable and clickable), I end up creating code that looks something like this:



document.getElementById("button1").onclick=function(){
    document.getElementById("button1").disabled="true";
}
document.getElementById("button2").onclick=function(){
    document.getElementById("button1").disabled="false";
}
and it has never worked, as much as I would like it to - despite the fact that setting "disabled" to be false should enable the input element.
Searching Google reveals this question on Stackoverflow: http://stackoverflow.com/q/6835165/1756941, which has an answer that does not meet StackOverflow's guidelines and expectations (ie. a link-only answer).

To make the code above work as intended is simple, and the solution is actually very simple.
just remove the quotes... And that's it!
Demo:

Code:

document.getElementById("button3").onclick=function(){
    document.getElementById("button3").disabled=true;
}
document.getElementById("button4").onclick=function(){
    document.getElementById("button3").disabled=false;
}
This is because the disabled attribute on an input element is a boolean, and text is always considered to be true. However you can find this out yourself!
Demo:


Code:

document.getElementById("button5").onclick=function(){
if ("false"){alert("\"false is true! (as a string)\"");}else{alert("\"false is not true! (as a string)\"");};
if ("false"==true){alert("\"false is true! (compared to true)\"");}else{alert("\"false is not true! (compared to true)\"");};
}
This seems illogical, as even as a text, false should be considered as false, especially when set as an attribute, but then again. This is javascript we're talking about...