Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check and uncheck all checkboxes in an html table with checking/unchecking one check box?

I have a table, with rows, every row has a check box, and there is a main check box at the thead. My code:

<table border="1">
    <thead>
        <tr>
            <th><input type="checkbox" id="allcb" name="allcb"/></th>
            <th>values</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" id="cb1" name="cb1"/></td>
            <td>value1</td>
        </tr>
        <tr>
            <td><input type="checkbox" id="cb2" name="cb2"/></td>
            <td>value2</td>
        </tr>
        <tr>
            <td><input type="checkbox" id="cb3" name="cb3"/></td>
            <td>value3</td>
        </tr>
    </tbody>
</table>

(also try it here)

Could anyone help me, how to do that if I check the main check box at the top, all check boxes will be checked, if I uncheck the main, all checkboxes will be unchecked. Thank you if you help me!

like image 234
victorio Avatar asked Jul 23 '13 15:07

victorio


2 Answers

Working Demo http://jsfiddle.net/xYAfj/2/

$('#allcb').change(function(){
    if($(this).prop('checked')){
        $('tbody tr td input[type="checkbox"]').each(function(){
            $(this).prop('checked', true);
        });
    }else{
        $('tbody tr td input[type="checkbox"]').each(function(){
            $(this).prop('checked', false);
        });
    }
});

Shorter Code

Working Demo http://jsfiddle.net/cse_tushar/4tss8/

$('#allcb').change(function () {
    $('tbody tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
like image 94
Tushar Gupta - curioustushar Avatar answered Oct 25 '22 16:10

Tushar Gupta - curioustushar


$(function(){
       $("#allcb").click(function() {
       var chkBoxes = $("input[id^=cb]");
       chkBoxes.prop("checked", !chkBoxes.prop("checked"));
   }); 
});

http://jsfiddle.net/7f7Kz/2/

like image 44
Prashanth Thurairatnam Avatar answered Oct 25 '22 18:10

Prashanth Thurairatnam