json1
json1

Reputation: 93

Boolean("false") returns true.. any alternative?

I am using jquery to write true and false strings to data- html attributes. However when I write false to one of the attributes, and then check it it false, it returns true. I also read online that it supposed to do that, which really makes no sense at all.

Does anyone have an alternative? Any help would be really appreciated!

(function() {
    // $(".opt-header").click(function () {
    $(document).on("click", ".opt-header", function() {
        console.log($(this).attr("data-is-panel-activated"));
        var is_activate = Boolean($(this).attr("data-is-panel-activated"));
        $(this).siblings(":not(.opt-group-toggle)").slideToggle(300);
        console.log(is_activate);
        if (is_activate) {
            $(this).find(".fa-angle-right").replaceWith("<i class='fa fa-angle-down'></i>");
            $(this).attr("data-is-panel-activated", "false");
        } else {
            $(this).attr("data-is-panel-activated", "true");
            $(this).find(".fa-angle-down").replaceWith("<i class='fa fa-angle-right'></i>");
        }
    })
})();

Upvotes: 0

Views: 1345

Answers (2)

slebetman
slebetman

Reputation: 113866

The simplest fix would be:

var is_activate = $(this).attr("data-is-panel-activated") !== "false";

or

var is_activate = $(this).attr("data-is-panel-activated") === "true";

depending on which semantics makes more sense for your code.

Upvotes: 0

omarjmh
omarjmh

Reputation: 13888

Boolean('false') will return true because the string 'false' is truthy.

You could just run a check to see if the string equals 'false':

if ($(this).attr("data-is-panel-activated") === 'false') {
   .....
}

Upvotes: 1

Related Questions