开发者

How do I toggle a checkbox when you click the enclosing <li> using JQuery?

I have some html like:

<ul class="myclass">
   <li><input type="checkbox"/>some text</li>
   <li><input type="checkbox"/>some text</li>
   <li><input type="checkbox"/>some text</li>
</ul>

I want the checkboxes to be toggled either by clicking the checkboxes, or any part of the

  • I tried the following jquery:

            $('ul.myclass li').click(
                    function() {
                        var cb = $(this).find(":checkbox")[0];
    
                        if (!$(cb).attr("checked")) {
                            $(cb).attr("checked", "checked");
                        } else {
                            $(cb).removeAttr("checked");
                        }
                    }
             );开发者_如何学Python
    

    Which works fine for when I click the text. But, now the checkboxes themselves dont actually work. It appears to be undoing the act of clicking on the checkbox.

    How do I prevent this?


    You can fix it by adding this:

    $('ul.myclass li input').click(
        function(event){
            event.stopPropagation();
        });
    

    basically the problem is that when you click on the checkbox, it is checked, but then the parent li's click event fires unchecking it. The code above prevents the li's event from firing.


    He's my version using the new .prop api from jQuery 1.6

    http://jsfiddle.net/7w82S/1/


    you could also use this code

    $('ul.myclass li').click(function(){
      $('input', this).attr('checked',true);
    });
    

    On clicking the li element the child input element is selected and it's checked value is set to true.

    You can check and uncheck by checking the value of the checked attribute.

    $('ul.myclass li').click(function(){
        var myInput = $('input', this)
        if(myInput.attr('checked')){
           myInput.attr('checked', false);
        }
        else{
           myInput.attr('checked', true);
        }
    });
    
  • 0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新问答

    问答排行榜