Test if at least one checkbox is checked

In this example, a submit button is disabled if none of the checkboxes are checked and enabled if at least one is checked.

<form>
   <!-- bunch of checkboxes like: -->
   <input type="checkbox" ... >
   <input type="checkbox" ... >

   <!-- submit button, defaults to disabled -->
   <input type="submit" value="submit">
</form>

The trick is that you can use .is(":checked") on a jQuery object full of a bunch of elements and it'll return true if any of them are checked and false if none of them are. AND, using .attr() for the disabled attribute with that boolean value will enable/disable that button.

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});

Comments

  1. User Avatar
    Bakaburg
    Permalink to comment#

    That’s net!

  2. User Avatar
    beh
    Permalink to comment#

    elegant solution

  3. User Avatar
    r
    Permalink to comment#

    so nice

  4. User Avatar
    Jeff
    Permalink to comment#

    Thanks! Exactly what I needed!

  5. User Avatar
    Kushal Jayswal
    Permalink to comment#

    can we do the same with UL LI structure, like I use custom selectbox and it will convert SELECT – OPTION Tags to UL – LI, so we will be having

      li class="selected"  

    while clicking on the LI and I want atleast ONE LI has CLASS selected there. And if not there it should give alert and not able to refresh the page.

    Can you help me?

  6. User Avatar
    vvbnvbn
    Permalink to comment#

    vbnvbnvbn

  7. User Avatar
    Hasin
    Permalink to comment#

    That’s great!! you’re programmer ninja! ;)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag