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.
To group checkboxes, click and drag the selection box around the checkboxes you'd like to group and then click Group checkboxes in the right sidebar. F. Label the fields - Note, labeling checkboxes helps to set up conditional logic for the checkboxes.
change(function() { $("#myform input:checkbox"). attr("checked", false); $(this). attr("checked", true); }); This should work for any number of checkboxes in the form.
If you want to allow the user to check only one checkbox from a group of the checkboxes, it can be done easily using jQuery. At first, include the jQuery library. To modify the default functionality of checkboxes and use like the radio buttons, you need to restrict the user to select multiple checkboxes.
There is a form with multiple checkboxes and we're going to make sure that at least one is checked using pure JavaScript. To set a custom validation error message, we will use setCustomValidity() method.
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;
}
});
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:
$('[id^="subscriber_"] :checkbox')...
This is called the Attribute Starts With Selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With