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.
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:
If you are unfamiliar with logical operators: XOR. I highly recommend getting familiar with all your logical operators. In this case an exclusive OR saves us from:
or this confusing mess:
This probably is/should be a jQuery plugin.