Select and de-select all checkboxes using jQuery

1 minute read

On almost every application I’ve worked on, there was a similar user story:

When i visit the page showing the list of unpaid/unprocessed things, I want to be able to select some of them to process automatically.

The best way to do this is with checkboxes, and a simple form that will submit to a given path, collecting the items you need to process.

Basically the next user story after that one is: I want to be able to select all checkboxes, so I don’t have to click each one if there are plenty of them.

This is where the story would get complicated, but it is really easy to do.

Let’s say that you have a check_box with an id of #select-all-checkboxes and that your form contains checkboxes with a class of .selectable-checkbox like this:

<input id="select-all-checkboxes" type="checkbox" value="1/" />
<form action="/action" method="post">
  <input class=".selectable-checkbox" name="checkbox_name[]" type="checkbox" value="1" />
  <input class=".selectable-checkbox" name="checkbox_name[]" type="checkbox" value="2" />
</form>

The solution to toggle them all is very easy, with JavaScript:

$('#select-all-checkboxes').change(function() {
  var is_checked = this.checked;
  $('.selectable-checkbox').each(function() {
    this.checked = is_checked;
  });
});

or with CoffeeScript:

$('input#select-all-checkboxes').change ->
  is_checked = @.checked
  $('.selectable-checkbox').each ->
    @.checked = is_checked
    return

And that is about it, now you have select/de-select all checkboxes working on your site. Be sure to wrap the above code in a $(document).ready(function() {}); or some other initialiser that is fit for your application.

Comments