user3504335
user3504335

Reputation: 177

Checkbox to toggle all selection

I have this javascript code

    // Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    }
});

And I have this

<form action="" method="POST">    
Toggle All : &nbsp;&nbsp;
<input type="checkbox" name="select-all" id="select-all" />

then at my table I have multiple checkbox

<input type="checkbox" name="checkbox-1" id="checkbox-1" value="1"> Select
<input type="checkbox" name="checkbox-2" id="checkbox-2" value="2"> Select
<input type="checkbox" name="checkbox-3" id="checkbox-3" value="3"> Select
<input type="checkbox" name="checkbox-4" id="checkbox-4" value="4"> Select

When I click on toggle all, it does not check checkbox-1 to checkbox-4

What went wrong in my javascript code.

Thanks!! I want to actually do a function that will send all the value of checkbox1-4 by post when they are checked on form submit.

Upvotes: 0

Views: 120

Answers (1)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

Simply do like this.

$('#select-all').click(function(event) {
    $(':checkbox').prop("checked", this.checked);
});

You do not need to loop through each checkbox to check all.

Demo

Wrap the code in dom ready if your script is in head tag

$(document).ready(function() {
    $('#select-all').click(function(event) {
        $(':checkbox').prop("checked", this.checked);
    });
});

Upvotes: 3

Related Questions