Saswat
Saswat

Reputation: 12806

Unchecking all checkboxes having same class

I have a script which checks all the checkboxes that have same class.

However, I have put a condition of unchecking all of them which is not working.

Here's my code

function check_all() {
    if ($('#all_check').prop("checked")) {
        $('.chk').prop("checked", "true");
    } else {
        $('.chk').prop("checked", "false");
    }
}

The line $('.chk').prop("checked", "false"); is having some problem, but what I can't find out.

Only this section of the code is not working.

Upvotes: 3

Views: 8917

Answers (7)

Firnas
Firnas

Reputation: 1695

The only problem I see in your code is the double quotes for true and false

function check_all() {
  if ($('#all_check').prop("checked")) {
    $('.chk').prop("checked", true);
  } else {
    $('.chk').prop("checked", false);
  }
}

You may also simplify as follows,

function check_all() {
  $('.chk').prop("checked", $('#all_check').prop("checked"));
}

Because the $('#all_check').prop("checked") returns either true or false. So that will be set to the checked property of the checkboxes with class .chk

Upvotes: 3

Gokul E
Gokul E

Reputation: 1386

Just do with .attr() function in jQuery

function checkall() {
    $('.chk').attr('checked', $('#all_check').is(':checked'));
}

Upvotes: 0

som
som

Reputation: 4656

True and False should be a boolean value. You assign string value in prop function.

 $('.chk').prop("checked", true);
 $('.chk').prop("checked", false);

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16754

The shortest way:

function check_all() {
  $('.chk').prop( "checked", $('#all_check').is(":checked") );
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

This will do

function check_all() {
     $('.chk').prop("checked", $('#all_check').is(":checked"));
}

Upvotes: 1

bipen
bipen

Reputation: 36531

you don't need "".pass boolean

$('.chk').prop("checked", true);
$('.chk').prop("checked", false);

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Just remove the quotes around true and false. They are data types and not strings.

function check_all() {
    if ($('#all_check').prop("checked")) {
        $('.chk').prop("checked", true);

    } else {
        $('.chk').prop("checked", false);

    }
}

Upvotes: 8

Related Questions