4

I've been looking through posts trying to find the answer, but haven't had any luck, so hoping someone can point me in the right direction.

When I use the following code, it checks all the input boxes and it unchecks them. However, if I click the check all again, it doesn't check them all. Why is that?

JQuery

  $('document').ready( function() {
    $('.check_boxes').click( function() {
      if ( $(':checkbox').attr('checked')) {
        $(':checkbox').attr('checked', false);
      } else {
        $(':checkbox').attr('checked', true);
      }     
    });
});

HTML

<input type="checkbox" class="check_boxes" id="check_all" />

3 Answers3

2

Try this:

js

  $('document').ready( function() {
    $('.check_boxes').click( function() {
      if ( $('input:checkbox').prop('checked')) {
        $('input:checkbox').prop('checked', true);
      } else {
        $('input:checkbox').prop('checked', false);
      }     
    });
});

fiddle

Alex Char
  • 32,879
  • 9
  • 49
  • 70
0

i think you need this simple code:

$('document').ready( function() {
$('.check_boxes').click( function() {
  if ( $(':checkbox').prop('checked')) {
    $(':checkbox').prop('checked', true);
  } else {
    $(':checkbox').prop('checked', false);
  }     
 });
});
DolDurma
  • 15,753
  • 51
  • 198
  • 377
0

Actually once you click on the checkbox, the first if is always true. Hence all checkeboxes get unchecked (including the one you clicked).

I assume you wanted this behavior: http://jsfiddle.net/vhLMN/18/

$('document').ready( function() {
    $('.check_boxes').click( function() {
      if ( !this.checked ) {
        $('.flip_us :checkbox').attr('checked', false);
      } else {
        $('.flip_us :checkbox').attr('checked', true);
      };     
    });
});

BTW. There is no label attribute on inputs. You should fix this unless you are using some framework that uses it to create actual label tag.

Nux
  • 9,276
  • 5
  • 59
  • 72