“None of the Above” Checkbox with jQuery
• Austin Pray • View Sauce • Edit
Demo
See the Pen Smart Checkboxes by Austin Pray (@austinpray) on CodePen.
Source
Problem
I had a friend last night ask me:
Anyone good at jQuery want to tell me if the following is a convoluted?
He had a group of checkboxes:
- option 1
- option 2
- option 3
- none of the above
He wanted them to behave such that:
- When “none of the above” is checked: all the other options become unchecked and disabled.
- When “none of the above” is unchecked: all the other options become enabled again.
There is nothing really wrong with the jquery one-liner my friend came up with. However I wanted a solution that didn’t rely on the user having to uncheck “none of the above” before being able to click another option. So:
- When “none of the above” is checked: all of the other options become unchecked.
- When an option other than “none of the above” is selected and “none of the above” is already checked: “none of the above” should be automatically unchecked.
Solution
Approach
Each time a checkbox in the group is checked:
- Loop through all of the checked boxes and get their values.
- If “none of the above” is among the values: decide which ones to uncheck based on the element that was just clicked.
Deciding when to uncheck
We loop through all of the checked boxes. For each element in the loop we evaluate this statement to determine if we should uncheck it:
\[A = \text{User checked "none of the above"}\\ B = \text{Current element in the loop is "none of the above"}\\ A \oplus B \equiv (A \rightarrow B) \rightarrow (\neg(B \rightarrow A))\]or:
If you are unfamiliar with logical operators: XOR. In this case an exclusive OR saves us from:
\[A = \text{User checked "none of the above"}\\ B = \text{Current element in the loop is "none of the above"}\\ (\neg A \wedge B) \vee (A \wedge \neg B)\]or this confusing mess:
Conclusions
This probably is/should be a jQuery plugin.