Toggle checkboxes

I have a table of elements, each of which has a checkbox for selecting or exiting. Since the list of items can be very long, I want to offer a “global” checkbox to check all checkboxes or disable them according to the setting of this global checkbox. I created jQuery code that does just that, but unfortunately, only once. I can’t switch settings again and again. Any thoughts why? Thank!

Here is my code:

jQuery('#ci-firmware-assign-toggle-checkbox').click(function(){
    if(jQuery('#ci-firmware-assign-toggle-checkbox').is(":checked")) {
        jQuery('tbody .ci-firmware-assign-checkbox').each(function(){
            if(!jQuery(this).attr("checked")) {
                jQuery(this).attr('checked', true);
            };
        });
    } else {
        jQuery('tbody .ci-firmware-assign-checkbox').each(function(){
            if(jQuery(this).attr("checked")) {
                jQuery(this).attr('checked', false);
            };
        });
    }
});
+4
source share
3 answers
jQuery('#ci-firmware-assign-toggle-checkbox').change(function(){   
   $('.ci-firmware-assign-checkbox').prop("checked", $(this).is(":checked"))
});
+1
source

I did it like this:

jQuery('#ci-firmware-assign-toggle-checkbox').click(function(){   
if(jQuery('#ci-firmware-assign-toggle-checkbox').is(":checked")) {
    
   $( '.ci-firmware-assign-checkbox' ).prop( "checked", function() {
        return true;
    })
    
} else {
   $( '.ci-firmware-assign-checkbox' ).prop( "checked", function() {
        return false;
    })
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='ci-firmware-assign-toggle-checkbox' type='checkbox' />Toggle All<br/>
<input id='1' type='checkbox' class='ci-firmware-assign-checkbox' />Checkbox 1<br/>
<input id='2' type='checkbox' class='ci-firmware-assign-checkbox' />Checkbox 2
Run codeHide result

And it works fine

0
source
jQuery('#ci-firmware-assign-toggle-checkbox').click(function(){
    if(jQuery('#ci-firmware-assign-toggle-checkbox').is(":checked")) {
        jQuery('tbody .ci-firmware-assign-checkbox').each(function(){
            if(!jQuery(this).**prop**("checked")) {
                jQuery(this).**prop**('checked', 'checked');
            };
        });
    } else {
        jQuery('tbody .ci-firmware-assign-checkbox').each(function(){
            if(jQuery(this).**prop**("checked")) {
                jQuery(this).**removeProp**('checked');
            };
        });
    }
});

attributes → HTML - make changes only in html

properties -> DOM - make changes to dom javascript state objects

0
source

Source: https://habr.com/ru/post/1599069/


All Articles