Reputation: 611
i am trying to add class to checkbox label if checkbox is already checked. i am doing this with jQuery each function but it adds class to all checkboxes label when i refresh the page.
$('label.checkbox').each(function() {
if ($('.checkbox input[type="checkbox"]').is(':checked')) {
$('label.checkbox').addClass('checked');
}
});
HTML
<label class="checkbox">
<span>Title</span>
<input type="checkbox" checked="checked" name="" />
</label>
Upvotes: 1
Views: 5303
Reputation: 240868
Using the jQuery :checked
selector, you could select all checked input elements and then add the class to the parent label element. No need for a loop.
$('input:checked').parent('label').addClass('checked');
Upvotes: 1