Reputation: 75
How to restrict user to select not more than 10 asp.net checkboxes on button click event , if user select more than 10 checkboxes then alert box will pop up that you can not select more than 10 checkboxes?
Upvotes: 0
Views: 664
Reputation: 156055
You can use a CustomValidator
and implement its ServerValidate
event (and, optionally, do the same thing on the client via its ClientValidationFunction
).
Maybe something like this (if you're using jQuery):
<asp:CheckBoxList ID="Checkboxes" runat="server" />
<asp:CustomValidator ID="CheckboxValidator" runat="server" Display="None" ClientValidationFunction="CheckboxValidator_ClientValidate" OnServerValidate="CheckboxValidator_ServerValidate" ErrorMessage="Too many selections" />
<asp:ValidationSummary runat="server" />
<script type="text/javascript">
function CheckboxValidator_ClientValidate(sender, args) {
args.IsValid = jQuery('#<%=Checkboxes.ClientID%> input:checked').length < <%= MaximumSelections %>;
}
</script>
protected const int MaximumSelections = 10;
protected void CheckboxValidator_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = Checkboxes.Items.Cast<ListItem>().Where(i => i.Selected).Count() < MaximumSelections;
}
Upvotes: 1
Reputation: 1497
If there are not many check boxes on the page, then create a onlcick javascript function for the checkbox and loop through all the check box to see if more than 10 is checked.
If there are a lot of checkbox on your page, then increment a variable when the checkbox is clicked and decrement it when its unchecked. You will have the count always which you can check to display the alert.
Upvotes: 2