Totally simple jQuery method for selecting all checkboxes in a form

It’s a common problem with a dozen different solutions – if you’ve ever needed to add a ‘select all’ checkbox to a form in order to make your users’ lives easier then you’ll have searched for a simple way to do it. If you’re using jQuery here’s a very simple method that’s as easy as can be:

$( '.selectall' ).click( function () {
    $( this ).closest( 'form' ).find( ':checkbox' ).attr( 'checked' , this.checked );
});

You can replace the form identifier with whatever container you choose (fieldset can be useful if your form is split up like that). This code will cause all the checkboxes in the form to be toggled when you toggle any checkbox that has the selectall class.

Simple.

UPDATE: Modified code to be slightly more efficient as suggested by Jamy Golden.

Tags: , , ,

2 Responses to “Totally simple jQuery method for selecting all checkboxes in a form”

  1. Jamy Golden October 18, 2012 at 4:16 pm #

    Hey Hugh :p

    I think the following would be very slightly more efficient. Not really important or anything but, here it is:
    $( this ).closest( ‘form’ ).find( ‘:checkbox’ ).attr( ‘checked’ , ‘checked’ );

    • Hugh Lashbrooke October 18, 2012 at 5:27 pm #

      Agreed that closest() would be more efficient. I would still keep ‘this.checked’ on at the end in order to enable proper toggling.

      I’ll update the code :)

Leave a Reply

css.php
Post
Comments