Nicola Bertelloni
Nicola Bertelloni

Reputation: 333

Trigger checkbox change class in Jquery

I am new to jQuery. I am trying to make a switcher using a checkbox. At the moment I have gone this far

$(function() {
  $('input.cbx').on('change', function() {
    if ($(this).prop("checked", true)) {
      $('body').addClass('dark');
    } else if ($(this).prop("checked", false)) {
      $('.body').addClass('light');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="dn" type="checkbox" class="cbx hidden" />
<label for="dn" class="lbl"></label>

As you can see the checkbox stay checked after the first click, I imagine is a noob situation but, can you help me please?

Upvotes: 4

Views: 11814

Answers (2)

Adil
Adil

Reputation: 148120

You are actually setting the checked property instead of getting.

$('input.cbx').on('change', function() {
    if($(this).prop("checked") ==  "true")
    {
      $('body').addClass('dark');
    } else if($(this).prop("checked") ==  "false")
    {
        $('.body').addClass('light');
    }
});

You can use this.checked or $(this).is(":checked") instead of $(this).prop("checked")

$('input.cbx').on('change', function() {
    if(this.checked) 
       $('body').addClass('dark');
    else
       $('.body').addClass('light');        
});

You can also use toggleClass

$('input.cbx').on('change', function() {     
     $('.body').toggleClass('light');        
});

Note: I could not see any element with class body? You probably need to assign class to label. If you want to apply the toggle effect to body then remove dot

Live Demo

HTML

<body class="cbx">
<input id="dn" type="checkbox" class="cbx hidden"/>
      <label for="dn" class="lbl">123</label>
</body>

Javascript

$('input.cbx').on('change', function() {     
     $('body').toggleClass('light');        
});

Upvotes: 6

guradio
guradio

Reputation: 15555

$('input.cbx').on('change', function () {
    if ($(this).is(":checked")) {
        alert('checked');
    } else {
        alert('not checked');
    }
});

DEMO You can check if the checkbox is check using $(this).is(":checked")

Upvotes: 0

Related Questions