2

below is code , both code works but i am trying to findout which is more perfect for browsers

Which code is right?

   <script>

document.getElementById("firstbtn").disabled=true;

</script>

or

<script>

document.getElementById("firstbtn").disabled='true';

</script>

also when we compare in

if(document.getElementById("firstbtn").disabled ==true)

or

if(document.getElementById("firstbtn").disabled =='true')
1
  • A related subject (but actually a different issue) is the difference between the disabled attribute in the HTML tag and the disabled property of the DOM object, which is another great source of confusion. Commented Oct 11, 2013 at 9:55

2 Answers 2

3

Use a boolean. The string only works because when it is cast to a boolean it is evaluated as true. If you were to assign "false" then that string would also be evaluated as true.

Sign up to request clarification or add additional context in comments.

1 Comment

Thumb rule: strings with values like 'true', 'YES', 'Y'... are normally meaningless in languages with actual data types.
1

It's important to understand which values evaluate to false in JavaScript. Falsy values are: undefined, null, NaN, 0 -0, "", and false. This means that everything else evaluates to true:

document.getElementById("firstbtn").disabled=true /* True */
document.getElementById("firstbtn").disabled="true" /* True */
document.getElementById("firstbtn").disabled="false" /* True */
document.getElementById("firstbtn").disabled="banana" /* True */
document.getElementById("firstbtn").disabled=1 /* True */
document.getElementById("firstbtn").disabled=4723598495 /* True */
document.getElementById("firstbtn").disabled=false /* False */
document.getElementById("firstbtn").disabled="" /* False */
document.getElementById("firstbtn").disabled=0 /* False */
document.getElementById("firstbtn").disabled=NaN /* False */

Because of this and as you can see above, "false" is evaluated to true as it is a string with length greater than 0.

On the subject of which is right, the answer would be that both are. Both get the job done. You may as well just use disabled=true, however, to avoid potential confusion at a later date.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.