Ilja
Ilja

Reputation: 46479

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.

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/

Upvotes: 2

Views: 1358

Answers (3)

kornieff
kornieff

Reputation: 2557

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.

Upvotes: 1

rrk
rrk

Reputation: 15846

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>

Upvotes: 7

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

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>

Upvotes: 2

Related Questions