Select all checkboxes with JQuery

< Back to blog | Add a comment

Posted: 6th Mar 2009
Categories: Web Development Tips and Tricks
Tags: web development jquery checkboxes permissions select all

blog-checkboxes

We have just built a cool 'select all checkboxes' function in JQuery and released the code. It is for administrators of Halogy to be able to simply grant permissions to their users at a category level, but if they want to they can open up the category and grant individual permissions.

Just make sure you put the select all checkbox inside a div giving it a class of 'selectall', and put the other checkboxes in another div next to it. The see more function opens up the div containing the child checkboxes.

Demo:

(see more)





Code:

<script type="text/javascript">
$(function(){
    $('.selectall').click(function(){
        $el = $(this).parent('div').next('div').children('input[type="checkbox"]');
        $flag = $(this).attr('checked');
        if ($flag) {
            $($el).attr('checked', true);
        }
        else {
            $($el).attr('checked', false);
        }
    });
    $('.seemore').click(function(event){
        event.preventDefault();
        $el = $(this).parent('div').next('div');
        $($el).toggle('400');
    });
});
</script>

Comments

By Stu Green on 6th Mar 2009

Also, you can cycle through checkboxes with this cool bit of JQuery code:

$('input[type="checkbox"]').each(function(){
if ($(this).attr('checked')) {
$flag = true;
}
});

By Ryan Fyfe on 21st Aug 2010

Hey Stu - I randomly came across this post through Google's Search through social circle..

I use jquery class selectors as much as possible to really reduce the code needed. For example for check all checkboxes:

function ToggleCB(Element){
$('.cb').attr('checked', $(Element).attr('checked'));
}

Add a comment






{captcha}


Back to top