Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery auto-check checkbox from same table

Tags:

jquery

I have this code:

HTML

<table class=tbl>
    <tr>
        <td>
            <input class='c1' type='checkbox'>
            <label>Ceckbox1</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
    </tr>
</table>
<table class=tbl>
    <tr>
        <td>
            <input class='c1' type='checkbox'>
            <label>Ceckbox1</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
        <td>
            <input class='c2' type='checkbox'>
            <label>Ceckbox2</label>
        </td>
     </tr>
   </table>

JavaScript

 $('.c2').click(function () {
     if ($(this).parent().find('.c2').is(':checked')) {
         alert('all are checked');
     } else {
         alert('none are checked');
     }
 });

I am trying, with no result, to use jquery to auto-check 'c1' only when all the 'c2' from the same 'tbl' are checked. The count of 'c2' can vary as can the count of 'tbl'.

like image 856
user1885099 Avatar asked Dec 20 '12 14:12

user1885099


People also ask

How to check checkbox dynamically in jQuery?

Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc.

How to get dynamic checkbox checked value in jQuery?

$('#envoyer'). click(function(e){ var myArray = new Array(3); for ( var j = 0; j < 3; j++) { var check=$('input:checkbox[name=checkbox'+j+']').is(':checked'); if(check==true) myArray[j]=$('input:checkbox[name=checkbox'+j+']'). val(); // Alert Current Selection // alert('check ' + " " + myArray[j] ); } });

How to checked the checkbox using jQuery?

There are two methods by which you can dynamically check the currently selected checkbox by changing the checked property of the input type. Method 1: Using the prop method: The input can be accessed and its property can be set by using the prop method.


1 Answers

You can see if all the checkboxes are checked by comparing the total number of checkboxes to the number of checked boxes, within the same parent tr. Try this:

$('.c2').change(function () {
    var $parent = $(this).closest('tr');
    var allChecked = $('.c2', $parent).length === $('.c2:checked', $parent).length;
    $('.c1', $parent).prop('checked', allChecked);
});

Example fiddle

like image 91
Rory McCrossan Avatar answered Oct 01 '22 20:10

Rory McCrossan