Abdul Shakoor Kakar
Abdul Shakoor Kakar

Reputation: 611

If checkbox is checked add class to it's label

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

Answers (1)

Josh Crozier
Josh Crozier

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');

Example Here

Upvotes: 1

Related Questions