I don’t write a lot of JavaScript. Every now and then I need it to use it solve a design problem. Recently, I needed JavaScript that would make sure that only three checkboxes could be checked at once. Here’s what I came up with in case it’s helpful to someone else.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <script type="text/javascript" language="javascript">
var current_count = 0;
var max_count = 3;
function maxCheckbox(item) {
if(item.checked) {
if(current_count >= max_count) {
item.checked=false;
alert('You may only choose '+max_count+' checkboxes.');
} else {
current_count += 1;
}
} else {
current_count -= 1;
}
}
</script>
<input name="checkbox1" onclick="maxCheckbox(this)" type="checkbox" value="1" /> One
<input name="checkbox2" onclick="maxCheckbox(this)" type="checkbox" value="1" /> Two
<input name="checkbox3" onclick="maxCheckbox(this)" type="checkbox" value="1" /> Three
<input name="checkbox4" onclick="maxCheckbox(this)" type="checkbox" value="1" /> Four
<input name="checkbox5" onclick="maxCheckbox(this)" type="checkbox" value="1" /> Five |
Each time a box is clicked the script runs. If a check mark is being added then the script tests to see if the running total (current_count) is larger than the defined maximum (max_count). If so, then it undoes the checkmark and displays an alert, but if not, then it allows the check and adds one to the current tally. When a box is unchecked, the tally simply decreases by one.