toggleClass() is not working as expected on label click

Alright, I’m working on a solution for custom checkboxes, I nest checkbox inside label and hide it, add some css to labels pseudo elements to display custom checkbox.

Now I want to add class .checked to a label on its click so related styles are applied, but for some reason I can’t seem to get toggle class working, it simply doesn’t add the class (addClass and removeClass) work, but thats a bit of a “dirtier” sollution.

  • Change HTML checkbox checked attribute
  • How to validate for checkbox selection if all checkbox have same name?
  • Show hidden fields when checkbox is checked?
  • How to adjust size of Grecaptcha v2 iframe
  • check/uncheck bootstrap checkboxes with jQuery
  • HTML checkbox onclick called in Javascript
  • JS

    $('.label-checkbox ').on('click', function() {
      $(this).toggleClass('checked');
    });
    

    HTML

    <label class="label-checkbox" for="show-news">show news posts
      <input type="checkbox" name="show-news" id="show-news">
    </label>
    

    Fiddle

    https://jsfiddle.net/hhsxyknf/

  • Change input -> change checkbox model without click
  • How to adjust size of Grecaptcha v2 iframe
  • How to validate a form with multiple checkboxes to have atleast one checked
  • Call javascript function only when checkbox is NOT checked
  • How to collect checked values in checkboxes as a javascript array/string?
  • jQuery - Checkbox not being checked
  • 3 Solutions collect form web for “toggleClass() is not working as expected on label click”

    No need to bind click on label, you can just call on change of the checkbox.

    $('input[name="show-news"]').on('change', function() {
      $(this).closest('label').toggleClass('checked');
    });
    .checked {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <label class="label-checkbox" for="show-news">show news posts
      <input type="checkbox" name="show-news" id="show-news">
    </label>

    What you are doing is right, AFAIK. Check out this, do you want something like this? You may need to consider binding the event with the change event of the <input> than the <label>:

    $(function () {
      $('.label-checkbox input').on('change', function() {
        $(this).closest(".label-checkbox").toggleClass('checked');
      });
    });
    .checked {font-weight: bold;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <label class="label-checkbox" for="show-news">show news posts
      <input type="checkbox" name="show-news" id="show-news">
    </label>

    When label is clicked, you also click the checkbox; thus, you get two clicks and your class toggle goes to checked then immediately removes it.