18

I have a table with a checkbox at the start of each row. Each Checkbox has the ID of #tablecheckbox. The table header row has a check icon which should check all boxed in the table. How can I do this with jQuery?

6
  • What have you already tried? Commented Aug 16, 2013 at 5:29
  • 5
    ^^ and ID's should be unique. Commented Aug 16, 2013 at 5:29
  • Make your ids a class, then follow this link: stackoverflow.com/questions/426258/… Commented Aug 16, 2013 at 5:31
  • instead of using id try to use name attriubute it can help to check all check boxs. Commented Aug 16, 2013 at 5:32
  • Can you please show the code for your table (at least the header and a few body rows)? Commented Aug 16, 2013 at 5:38

2 Answers 2

6

Here head_checkbox is id of top header and person class is all row checkbox

 $('#head_checkbox').on('change', function () {
            if ($(this).is(':checked')) {
                $('.person').attr('checked', true);
            } else {
                $('.person').attr('checked', false);
            }
        });

        $('.person').click(function () {
            var total_length = $('.person').length;
            var total_checked_length = $('.person:checked').length;

            if (total_length == total_checked_length) {
                $('#head_checkbox').attr('checked', true);
            } else {
                $('#head_checkbox').attr('checked', false);
            }
        });
Sign up to request clarification or add additional context in comments.

2 Comments

live is deprecated since 1.7 on() should be used instead
I used to set document.getElementById("head_checkbox").checked attribute. Your approach seems more clean. Thanks.
2
       $('#head_checkbox').click(function () {
            if ($(this).is(':checked')) {
                $('.person').attr('checked', true);
            } else {
                $('.person').attr('checked', false);
            }
        });


        $('.person').click(function () {
            if ($('.person').length == $('.person:checked').length) {
                $('#head_checkbox').attr('checked', true);
            } else {
                $('#head_checkbox').attr('checked', false);
            }
        });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.