I have 5 checkboxes that I use as filters for a set of data (rails app) and I'm having a hard time getting the Javascript down to manipulate the checkboxes for what I need.
Conditions:
- If
all
is selected, uncheck any 'other' checkboxes but if unchecking this will leave none checked then keep it checked. - If no checkboxes are checked, set
all
to checked - If any 4 'other' checkboxes are checked, uncheck
all
Essentially, one of them must be checked at all times, with the all
filter being the default, however, all
cannot be checked when any of the others are checked and if all
is checked, then none of the others can be.
Code so far
jQuery(function($) {
// all checkbox
var all_checkbox = $('#orderStatusAll');
// 'other' checkboxes
var open_checkbox = $('#orderStatusOpen');
var complete_checkbox = $('#orderStatusCompleted');
var reactivated_checkbox = $('#orderStatusReactivated');
var canceled_checkbox = $('#orderStatusCanceled');
var status_filter_form = $('#orderStatusFilters');
var all_status_filters = status_filter_form.find('input[type=checkbox]');
var filter_status_all = $('#filterStatusAll').find('input[type=checkbox]');
var filter_status_other = $('#filterStatusOther').find('input[type=checkbox]');
all_status_filters.on('change', function() {
if ($(this).attr('id') === 'orderStatusAll' ) {
if (all_status_filters.not(':checked')) {
$(this).attr('checked', true);
$(this).closest('label.checkbox').addClass('checked');
} else {
filter_status_other.each(function() {
$(this).attr('checked', false);
$(this).closest('label.checkbox')
.removeClass('checked');
});
}
status_filter_form.submit();
} else if (all_status_filters.not(':checked')) {
all_checkbox.attr('checked', true);
all_checkbox.closest('label.checkbox').addClass('checked');
status_filter_form.submit();
} else {
all_checkbox.attr('checked', false);
all_checkbox.closest('label.checkbox').removeClass('checked');
status_filter_form.submit();
}
});
});
The above follows the logic I need but clearly it doesn't work. I'm not sure how to return true if all checkboxes are unchecked and the else if
part above is happening always and subsequently the first part of the if
statement under the orderStatusAll
is keeping the all
checkbox checked always.
Javascript isn't my strong suit so any help and understanding would be greatly appreciated! Thanks!
Aucun commentaire:
Enregistrer un commentaire