11

I'm trying to write a piece of jQuery code where, if all checkboxes are "unchecked", then all li tags have the class "disabled."

But, if one checkbox (any checkbox) is checked, then all [li] tags lose the class "disabled".

Many thanks!

3
  • Do you want to remove 'disabled' class if at least one checkbox is checkd OR EXACTLY one checkbox is checked? Commented Jul 21, 2009 at 16:28
  • I want it if at least one checkbox is checked. Commented Jul 21, 2009 at 17:15
  • Thanks RaYell, your code helped tremendously! Commented Jul 21, 2009 at 17:19

4 Answers 4

15
$(':checkbox').click(function () {
    $('li').toggleClass('disabled', !$(':checkbox:checked').length);
});
Sign up to request clarification or add additional context in comments.

18 Comments

You should use $('#myform input[type=checkbox]:checked') if you only want the checkboxes in a form with id myform.
I think you meant $("li") instead of $("*").
Yes, I notices that typo and fixed it.
You can replace the branch with a call to toggleClass instead of two different calls (one to addClass and one to removeClass): $('li').toggleClass('disabled', (count===0));
There is a shortcut for getting checkboxes instead of checking the type attribute: $(':checkbox:checked')
|
8

I came across this post by accident and I thought I would add my shilling worth:

jQuery(':checkbox').click(function()
{
    if (jQuery(this).is(':checked'))
    {
        alert("Checked");
    }
    else
    {
        alert("Unchecked");
    }
});

1 Comment

This doesn't apply a class, or examine all other checkboxes, so doesn't really solve the OP's problem. Adding a click handler to checkboxes and then seeing if the clicked item is checked is kinda the easy part :(
5

Slight modification of RaYell's, which will include any dynamically added checkboxes:

$(':checkbox').live('click', function () {
    $('li').toggleClass('disabled', !$(':checkbox:checked').length);
});

2 Comments

"change" is not a good event to capture for checkboxes. You should always use "click" (which is also fired when a checkbox is selected using the keyboard).
Excellent point, and one I should have remembered from previous code. IE doesn't handle "change" on checkboxes, for starters.
1
$(':checkbox')
    .click(
        function() 
        { 
            $('li').toggleClass('disabled', $(':checkbox :checked').length <= 0));
        }
     );

EDIT: Thanks Ken for pointing out toggleClass method.

Comments