Reputation: 445
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.
Upvotes: 7
Views: 11227
Reputation: 78741
You should add a class to your subscriber divs, to make it easier to attach event handlers:
<div id="subscriber_1" class="subscriber">...</div>
<div id="subscriber_2" class="subscriber">...</div>
And use this jQuery:
$('.subscriber :checkbox').change(function () {
var $cs = $(this).closest('.subscriber').find(':checkbox:checked');
if ($cs.length > 3) {
this.checked = false;
}
});
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:
$('[id^="subscriber_"] :checkbox')...
This is called the Attribute Starts With Selector.
Upvotes: 12