1

I have an anchor element :

<a id="buyBtn" href="#" alt="Purchase" title="Buy now" data-enabled="true">

When it is clicked, I'm doing this:

enabled = $(this).data('enabled') == "true";
console.log(enabled);

However, the console shows false. I was initially using === but that was giving false, so I moved to ==.

4
  • What do you get from console.log($(this).data('enabled'))? Commented Oct 19, 2012 at 4:46
  • Working example showing what's at play here: jsfiddle.net/FsP3j/1 Commented Oct 19, 2012 at 4:48
  • @Cthulhu - The issue, in reality, is the OP did === "true" instead of === true. Face, meet palm, doh si doh. Commented Oct 19, 2012 at 4:51
  • @Cthulhu: That's not the issue at hand. The issue was that jquery automatically converts the string 'true' to boolean true. Commented Oct 19, 2012 at 4:51

1 Answer 1

10

The accepted answer for this question details why:

Retrieve boolean data from data attribute in jquery

jQuery's .data() method is smart enough to convert "true"/"false" data strings into real Boolean values.

The strict comparison operator checks types, and is failing because you are comparing a string to a boolean.

"true" === true // false
Sign up to request clarification or add additional context in comments.

1 Comment

oh, wow...sheesh. I would never have guessed that. Thank you.

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.