Fork me on GitHub

Hello my name is Pui, I am a web developer based in London.

jQuery - Check if more than one checkbox is checked

24 April 2014

Problem

​This is quite a specific solution. Basically the problem is that we have a section with many checkboxes and we would like to run a function when only ONE checkbox is checked. We then also want to run a function when NO checkboxes are checked.

In this case, the reason for this is to make a progress bar increase a certain percentage only once, so on click of only one checkbox. And then to decrease a certain percentage when there are no checkboxes checked.

Solution

We will write a function that runs whenever a user clicks a checkbox to count the number of checkboxes that are checked:

 $('#checkbox_outer input').change(function() {   if ($("#checkbox_outer input:checkbox:checked").length === 1) {     console.log('one checkbox checked');   } else if ($("#checkbox_outer input:checkbox:checked").length == 0) {     console.log('no checkbox checked');   } });

So what we are doing here is, when a user checks a checkbox:

  • Run a conditional to check that only one checkbox is checked
  • Else check that no checkboxes are checked

Within these If statements we can then run our functions.

About the author

Pui-Ling Lau, front end web developer and designer based in Kent and London

Pui is a User Experience developer working as a contractor in and around London.