I have two groups of checkboxes: Products and Countries. What I’m trying to do is to have two conditions:
-
Case 1: 1 country + many products
-
Case 2: many countries + 1 product
So, If I select 2 products I should be able to select only 1 country. If I select multiple countries I should be able to select only 1 product.
Currently, it doesn’t work as expected. When I check on the product and then check the second, the first product gets deselected and all become disabled. About the countries – I’m able to select all of them.
Here is a demo: https://jsfiddle.net/816obeLj/
Here is what I have so far
$(document).ready(function() {
var maxCountrySelection = 1;
var maxIndicatorSelection = 1;
var countryCheckboxes = $('input[type="checkbox"].countryCheckbox');
var indicatorCheckboxes = $('input[type="checkbox"].indicatorCheckbox');
countryCheckboxes.change(function() {
var selectedCountries = countryCheckboxes.filter(':checked');
var selectedIndicators = indicatorCheckboxes.filter(':checked');
if (selectedCountries.length > maxCountrySelection) {
countryCheckboxes.not(this).prop('checked', false).prop('disabled', true);
} else {
countryCheckboxes.prop('disabled', false);
}
if (selectedIndicators.length > 0) {
indicatorCheckboxes.not(':checked').prop('disabled', true);
} else {
indicatorCheckboxes.prop('disabled', false);
}
});
indicatorCheckboxes.change(function() {
var selectedCountries = countryCheckboxes.filter(':checked');
var selectedIndicators = indicatorCheckboxes.filter(':checked');
if (selectedIndicators.length > maxIndicatorSelection) {
indicatorCheckboxes.not(this).prop('checked', false).prop('disabled', true);
} else {
indicatorCheckboxes.prop('disabled', false);
}
if (selectedCountries.length > 0) {
countryCheckboxes.not(':checked').prop('disabled', true);
} else {
countryCheckboxes.prop('disabled', false);
}
});
});
2
Answers
Your first issue in the JsFiddle was that the country checkboxes did not have the
countryCheckbox
class in the html.Additionally, the js logic could be simplifed as in this working example: JSFiddle
Maybe like this: