layout | title | categories | tags | math |
---|---|---|---|---|
post |
“None of the Above” Checkbox with jQuery |
javascript |
jquery forms |
true |
See the Pen Smart Checkboxes by Austin Pray (@austinpray) on CodePen.
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>I had a friend last night ask me:
Anyone good at jQuery want to tell me if the following is a convoluted? {% highlight js %}
$('.gfield_checkbox input[value="none"]').change(function() { $ (this).parents('.gfield_checkbox').find('input:checkbox').not(this).prop('checked', false).prop('disabled', $(this)[0].checked); }); {% endhighlight %}
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.
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:
or:
{% highlight javascript %} if (A^B) { // uncheck everything else } {% endhighlight %}
If you are unfamiliar with logical operators: XOR. In this case an exclusive OR saves us from:
or this confusing mess:
{% highlight javascript %} if ((!A && B) || (A && !B)) { // uncheck everything else } {% endhighlight %}
This probably is/should be a jQuery plugin.