For use with multiple sets of Isotope filters. Select “all” by default, but if a filter is selected then remove the checkbox selection from all. If no filters are selected, choose “all” for the particular data-group. There is a dependency on the jQuery version. New versions of jQuery use prop to set the checkbox to on or off, old versions use attr. Very confusing. This particular CodePen is using jQuery 1.11.1.
See this snippet in action on CodePen
var filters = {}; function manageCheckbox( $checkbox ) { var checkbox = $checkbox[0]; var group = $checkbox.parents('.option-set').attr('data-group'); console.log ("group=" + group); // create array for filter group, if not there yet var filterGroup = filters[ group ]; if ( !filterGroup ) { filterGroup = filters[ group ] = []; } var isAll = $checkbox.hasClass('all'); // reset filter group if the all box was checked if ( isAll ) { delete filters[ group ]; if ( !checkbox.checked ) { checkbox.checked = 'checked'; } } // index of var index = $.inArray( checkbox.value, filterGroup ); if ( checkbox.checked ) { var selector = isAll ? 'input' : 'input.all'; $checkbox.siblings( selector ).removeAttr('checked'); if ( !isAll && index === -1 ) { // add filter to group filters[ group ].push( checkbox.value ); } } else if ( !isAll ) { // remove filter from group filters[ group ].splice( index, 1 ); // if unchecked the last box, check the all if ( $checkbox.siblings().filter(':checked').length == 0 ) { $checkbox.siblings('input.all').prop('checked', true); } } } $(function(){ $('#options').on( 'change', function( jQEvent ) { var $checkbox = $( jQEvent.target ); manageCheckbox( $checkbox ); }); });
Leave A Comment