1

I have two problems with checking and unchecking (select and deselect all) a checkboxlist:

  1. The parent checkbox does not check/uncheck.
  2. I need to only select the children.

Example:

http://jsfiddle.net/TheFiddler/v6wmV/,

$(document).ready(function(){
    $('.all').toggle(
        function() {
            $('.check').find('input[type=checkbox]').attr('checked', true);
        },
        function() {
            $('.check').find('input[type=checkbox]').attr('checked', false);
        });
});

Right now, I have the event on a class, and since the class is shared by both checkbox lists, they all toggle.

1

2 Answers 2

6

Demo

$(document).ready(function(){ 
    $('.all').click(function() {
        var $checkboxes = $(this).parent().find('input[type=checkbox]');
        $checkboxes.prop('checked', $(this).is(':checked'));
    });     
});  

HTML

<div class="check">
      <input type="checkbox" class="all" /> Check/Uncheck all<br />
      <input type="checkbox" /> 1<br />
      <input type="checkbox" /> 2<br />
      <input type="checkbox" /> 3<br />
      <input type="checkbox" /> 4<br />
      <input type="checkbox" /> 5<br />
      <input type="checkbox" /> 6<br />
      <input type="checkbox" /> 7
</div>
...
Sign up to request clarification or add additional context in comments.

2 Comments

this definitely works but you do NOT need the "? true : false" part, since "$(this).is(':checked')" already returns true or false. it's like saying "if(true){ true } else { false}"
Actually, it needs a !$(this).is('checked'), otherwise it doesn't do anything.
1

Nice post above. Yet another way using each function, though its not using the children only.

jQuery('.check-all').click(function() {
      jQuery('.checked-rec').each(function() {
        $(this).attr('checked', $('.check-all').is(':checked'));
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<thead>
  <tr>
    <th>
      <input type="checkbox" class="check-all">
    </th>
  </tr>
</thead>

<tbody>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

  <tr class="odd gradeX">
    <td>
      <input type="checkbox" class="checked-rec">
    </td>
  </tr>

</tbody>

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.