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
/
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/hhsxyknf/
Share edited Aug 24, 2015 at 8:37 Ilja asked Aug 24, 2015 at 8:35 IljaIlja 46.6k103 gold badges289 silver badges528 bronze badges 3- Can you create demo on jsfiddle – Tushar Commented Aug 24, 2015 at 8:37
- @Tushar jsfiddle/zLs7e8w4 – akash Commented Aug 24, 2015 at 8:37
- See Working Demo – Tushar Commented Aug 24, 2015 at 8:39
3 Answers
Reset to default 7No 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./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./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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745068743a4609415.html
评论列表(0条)