4

I simply want to check all of the check boxes on a page if a user clicks the "Select All" button.

In the body:

<button id="checkall">Select All</button>

jQuery:

<head>

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">
    $(document).ready(function(){
        $('#checkall').click(function () {
            $("input[type=checkbox]").each( function() {
            $(this).attr('checked', true);
        });
    });
    </script>
</head>

And the checkboxes are generated by a little bit of php:

echo '<li>';
echo '<input type="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>';
echo '</li>';

Can anyone tell me what I'm doing wrong?

0

4 Answers 4

10

You dont need the each statement. Just select all checkboxes and set the property checked = true.

$(document).ready(function(){
    $('#checkall').click(function () {
        $("input:checkbox").prop('checked', true);
    });
});

Note jQuery.prop() is a feature added to 1.6 and up. If you are on a version of jQuery prior to 1.6 you will need the following.

$(document).ready(function(){
    $('#checkall').click(function () {
        $("input:checkbox").attr('checked','checked');
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

bear in mind this will only check the boxes. Additional code will be necessary for unchecking.
1

Instead of selecting checkbox with tag name better assign it some class and select it with classname

  $(document).ready(function(){
      $('#checkall').click(function () {
           $(".checkbox").each( function(i,chkbox) {
             $(chkbox).attr('checked', true);
      });
     });
   });

php code

                 echo '<li>';
                echo '<input type="checkbox" class="checkbox" name="checkbox[]" value="'.$x.'" />'.$x.'<br/>';
                echo '</li>'; 

1 Comment

This still has one }); too few, and .each is kind of redundant here.
0

You just miss a }); for the .each(function(){} statement! There was no error else!

$(document).ready(function () {
    $('#checkall').click(function () {
        $("input[type=checkbox]").each(function () {
            $(this).attr('checked', 'checked');
            // or 
            // $(this).attr('checked', true);
        }); // you missed this one!!!
    });
});

1 Comment

jQuery.each() is not needed.
0

This Will Work, Short and handy Code

<script>
    $('#check_all').click(function () {
    $( this ).closest('form').find(':checkbox').prop( 'checked' , this.checked ? true : false );
})
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.