简体   繁体   中英

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.

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);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM