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" />
2
  • try using .prop instead of .attr Commented Jul 2, 2014 at 21:23
  • Ok here is your demo jsfiddle.net/vhLMN/14 what do you want here? Commented Jul 2, 2014 at 21:26

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. If one of the inputs is checked the check all input still stays checked :/
I thought you want a checkbox to check/uncheck all. Correct me if i'm wrong.
Yes that's true...just thought it would uncheck if one of the inputs were unchecked. I'm still learning js.
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.

1 Comment

nice catch, that should be id= thanks!
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);
  }     
 });
});

5 Comments

Here is the demo jsfiddle.net/vhLMN/17
Awesome, thank you! I wasn't too far off :) I tried using .prop() before and it didn't work the way I had the code. Now, how would I automatically uncheck the check all input if one of the inputs is unchecked?
Line 3 needs to be .prop too, correct? Otherwise my code doesn't work.
That does not work. See jsfiddle.net/vhLMN/21
Neither of those work, see jsfiddle.net/vhLMN/23

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.