Question

Basically I have a checkbox inside a td element and I want it to have one background color when the checkbox is checked and another background color when the checkbox is unchecked. So in other words I want it to highlight whether it's checked or not.

I tried to use the same solution as in here: Jquery toggle event is messing with checkbox value

But for some reason I can't get it working.

    $(document).ready(function(){
    $("input:checkbox").change(function() {
        if($(this).attr("checked") === "true") {
            // CHECKED, TO WHITE
            $(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"});
            return;
        }
        //NOT CHECKED, TO GREEN
        $(this).parent().css({"background" : "#b4e3ac", "-moz-border-radius" : "5px"});
    });
});

It does add the green background color but doesn't remove it. And if I leave a checkbox checked, refresh, the td is back to white and once clicking on the checkbox again, unchecking it, it changes the td's background to green.

I'm still new to this, have no idea what could be wrong here, been trying to figure it out for hours now. Such a simple thing but just can't get it working.

Was it helpful?

Solution

Change

if($(this).attr("checked") === "true")

to

if($(this).attr("checked") === true)

Snce you are comparing using strict equal the two data types must be the same.

typeof ( $(this).attr ( "checked" ) )

will let you know that it is of boolean type and you are comparing it to a string.

For more info see Comparison Operators

OTHER TIPS

There is a better way to see if the checkbox has been checked:

$(this).is(':checked')

It is a bit more robust.

if ($(this).attr("checked") === "true")

attr does not read HTML attributes. It's deceptive that way. If it did read attributes, the string value for checked would be 'checked' and not 'true'. But it doesn't do that.

What it actually does is read JavaScript object properties, only using attribute names instead of property names in the few places they differ. The checked property gives you a boolean value so there's no need to compare it to anything, you can just say:

if ($(this).attr('checked'))

or, even simpler, the totally equivalent:

if (this.checked)

best one is

if($("this").is(':checked'))
 {
   $(this).parent().css({"background" : "#ffffff", "-moz-border-radius" : "5px"})
 }

Check out this article on the difference between =, == and === in javascript. Or this on equality operators in js.

Try changing this:

$(this).attr("checked") === "true"

to this:

!!$(this).attr("checked") === true

This will convert any non-boolean to a boolean and allow your type safe comparison to work even if the string "true" is returned (if the string false is returned it will evaluate to true though....)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top