Change label when checkbox is checked

后端 未结 3 1840
说谎
说谎 2021-01-28 23:47

I have a lot of listst with checkboxes like so:

相关标签:
3条回答
  • 2021-01-29 00:23
    $(".filteritem").on('change', function(){
         $(this).closest('label').toggleClass('highlight');
    });
    

    FIDDLE

    0 讨论(0)
  • 2021-01-29 00:26

    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.

    0 讨论(0)
  • 2021-01-29 00:29

    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');
    });
    
    0 讨论(0)
提交回复
热议问题