Skip to content Skip to sidebar Skip to footer

Multiple Checkboxes To Trigger A Js Script

I have multiple lists generated inside a while loop. Each list has a group id assigned to it, and stored in a variable. Each list item has a checkbox. I want to be able to have a '

Solution 1:

Inside your select all change handler, you can select just the inputs that match your current groupID

jQuery(".cl-checkall").change(function() {
    jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]')
        .prop('checked', jQuery(this).prop("checked"));
});

This is effectively what you have already, but we're adding the data selector to the jQuery search to exclude the other checkboxes on the page.

The jQuery(this).data("groupid") (jQuery requires data attribute names to be lower case) will return the data attribute for the changed element, and the [data-groupID="x"] will only match elements with the groupID x

(As you now have multiple of them, you will probably also want to start using a class on the select-all checkbox instead of an ID, I've changed it to using .cl-checkall)

The same changes can be applied to the individual checkbox listener, only selecting the select-all with the matching data attribute.

jQuery('.cl-checkbox').change(function() { 
    if(false == jQuery(this).prop("checked")) {
        jQuery('.cl-checkall[data-groupID="' + jQuery(this).data("groupid") + '"]').prop('checked', false);
    }
    if (jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]:checked').length == jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]').length ){
        jQuery('.cl-checkall[data-groupID="' + jQuery(this).data("groupid") + '"]').prop('checked', true);
    }
});

Post a Comment for "Multiple Checkboxes To Trigger A Js Script"