user1386906
user1386906

Reputation: 1179

Change label when checkbox is checked

I have a lot of listst with checkboxes like so:

<ul>
   <li><label class="highlight"><input type="checkbox" id="1" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="223" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="32" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="42" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="54" class="filteritem">Lorem Ipsum</label</li>
</ul>

<ul>
   <li><label class="highlight"><input type="checkbox" id="43" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="343" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="342" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="53" class="filteritem">Lorem Ipsum</label</li>
   <li><label class="highlight"><input type="checkbox" id="55" class="filteritem">Lorem Ipsum</label</li>
</ul>

Every checkbox has an unique ID

I want to toggle the background-color of the label when it is checkt.

This is what i got but it does not work:

jQuery:

$(".filteritem").click(function(){
    $(this).toggleClass('highlight');
});

CSS:

.highlight {
    //change something
}

Upvotes: 0

Views: 8259

Answers (3)

Šime Vidas
Šime Vidas

Reputation: 186113

HTML:

<ul class="checkboxlist">
   <li><label><input type="checkbox" id="1"> Lorem Ipsum</label></li>
   <li><label><input type="checkbox" id="223"> Lorem Ipsum</label></li>
   <li><label><input type="checkbox" id="32"> Lorem Ipsum</label></li>
</ul>

JavaScript:

$( '.checkboxlist' ).on( 'click', 'input:checkbox', function () {
   $( this ).parent().toggleClass( 'highlight', this.checked );
});

Live demo: http://jsfiddle.net/MGVHX/1/

Notice that I use event delegation, instead of binding the same handler to every check-box.

Upvotes: 7

James Allardice
James Allardice

Reputation: 166071

You are currently trying to call toggleClass on the input element, not the label. You can use parent to get the label:

$(".filteritem").click(function(){
    $(this).parent().toggleClass('highlight');
});

Upvotes: 2

adeneo
adeneo

Reputation: 318372

$(".filteritem").on('change', function(){
     $(this).closest('label').toggleClass('highlight');
});

FIDDLE

Upvotes: 1

Related Questions