I would like to have an application where a user will enter data for arbitrary individuals. each individual will have a choice of a maximum of three of six options. I want help on how to force a maximum of three choices using jquery on any indivual.
here is a sample code
<div id="subscriber_1">
<input type=checkbox name=national>
<input type=checkbox name=international>
<input type=checkbox name=business>
<input type=checkbox name=entertainment>
<input type=checkbox name=religion>
<input type=checkbox name=sports>
</div>
the subscribers can run upto 20, like subscriber_1, subscriber_2, … subscriber_20. I will be grateful for your assistance.
You should add a class to your subscriber divs, to make it easier to attach event handlers:
And use this jQuery:
jsFiddle Demo
Explanation: On the change event of these checkboxes, we look for the closest parent that has the class
.subscriber. We get the checked checkboxes inside this div. If there are more than 3 (the currently checked one counts as well), we uncheck the current one.If you certainly don’t want to add classes, you can use this selector instead:
This is called the Attribute Starts With Selector.