3

First of all the fiddle: http://jsfiddle.net/6d82Q/1/

In my HTML I have:

<div class="myClass" data-status="true"></div>
<div class="myClass" data-status="false"></div>

I want to add a CSS-class to a div depending on the status:

$('.myClass').each(function()
{ 
    // compare status
    if($(this).data('status') == 'true')
    {
        $(this).addClass('myTrueClass');
    }
    else
    {
        $(this).addClass('myFalseClass');
    }
});

The Problem is, that always myFalseClass is added. My question is: How can the problem be fixed and why does it occur in the first place?

bluelDe
  • 395
  • 8
  • 17

3 Answers3

4

Try,

$('.myClass').each(function()
{ 
    if($(this).data('status'))
    {
        $(this).addClass('myTrueClass');
    }
    else
    {
        $(this).addClass('myFalseClass');
    }
});

Since .data(key) would automatically convert that "true" into a boolean.

DEMO

For sure, if you want to get that "true" as a string then just use .attr("data-status")

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
3

The .data() method will perform some auto-casting on [data-*] attributes, which makes passing data to the client very convenient.

As you're storing what would be auto-cast to a boolean, you can use:

if ($(this).data('status')) {
    ...
} else {
    ...
}

If you need to make sure that the value is true, and not just truthy (like a value of 1) then be sure to use a reference comparison:

if ($(this).data('status') === true) {
    ...
} else {
    ...
}

As an aside, there's no reason to call .each() when you could simply pass a function to .addClass():

$('.myClass').addClass(function () {
    return $(this).data('status') ? 'myTrueClass' : 'myFalseClass';
});
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

you have to do like this:

if($(this).data('status') === true)
{
    $('#out').append('true <br>');
}
else
{
    $('#out').append('false <br>');
}

UPDATED FIDDLE

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160