json1 json1 - 4 months ago 6
jQuery Question

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>");
}
})
})();

Answer

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') {
   .....
}