Check out this alternative approach that utilizes pure JavaScript without the need for jQuery:
function convertArgsToArray(args) {
var result = [];
for (var index = 0; index < args.length; index++)
result.push(args[index]);
return result;
}
function bindAction() {
var initialArgs = convertArgsToArray(arguments);
var action = initialArgs.shift();
var targetObj = initialArgs.shift();
var params = initialArgs;
return function() {
return action.apply(targetObj, params.concat(convertArgsToArray(arguments)));
};
}
var salutationItems = convertArgsToArray(document.getElementsByClassName('salutation'));
salutationItems.forEach(function(item) {
item.addEventListener('change', bindAction(function(checkbox, salutations) {
var checkedCount = salutations.filter(function(checkbox) { return checkbox.checked; }).length;
if (checkedCount >= 4)
checkbox.checked = false;
}, null, item, salutationItems), false);
});
To implement this code, place it inside a script block at the end of your <body>
tag and watch as it enforces a maximum limit of three checkboxes that can be checked simultaneously.
For testing purposes, here is a sample page you can use:
<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function convertArgsToArray(args) {
var result = [];
for (var index = 0; index < args.length; index++)
result.push(args[index]);
return result;
}
function bindAction() {
var initialArgs = convertArgsToArray(arguments);
var action = initialArgs.shift();
var targetObj = initialArgs.shift();
var params = initialArgs;
return function() {
return action.apply(targetObj, params.concat(convertArgsToArray(arguments)));
};
}
var salutationItems = convertArgsToArray(document.getElementsByClassName('salutation'));
salutationItems.forEach(function(item) {
item.addEventListener('change', bindAction(function(checkbox, salutations) {
var checkedCount = salutations.filter(function(checkbox) { return checkbox.checked; }).length;
if (checkedCount >= 3)
checkbox.checked = false;
}, null, item, salutationItems), false);
});
</script></body></html>