Changing checkbox parent css element if checkbox is checked or not checked

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

I tried using the same solution as here: jquery toggle event fiddling with checkbox value

But for some reason I can't get it to work.

    $(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 adds a green background color, but does not remove it. And if I leave the checkbox checked, refresh, td will go back to white and as soon as you click on this checkbox again, deselecting it, it will change the td background to green.

, , , . , .

+3
6

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

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

Snce, , , .

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

, boolean, .

.

+2

, :

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

.

+5

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

attr HTML. . , checked 'checked', 'true'. .

, JavaScript, , . checked , , :

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

, , :

if (this.checked)
+2

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

:

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

:

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

, "true" ( false, true, ....)

+1

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

+1
source

Source: https://habr.com/ru/post/1724088/


All Articles