Please note that the scenario is ASP.NET Webforms + Master - Content page which mess up the ids.
I have, say, three checkboxes
You could do this very easily with a CheckBoxList and a Dado.Validators which provides support for CheckBoxLists. Note this provides client-side and server-side validation.
<asp:CheckBoxList ID="cblCheckBoxList" runat="server">
<asp:ListItem Text="Check Box (empty)" Value="" />
<asp:ListItem Text="Check Box 1" Value="1" />
<asp:ListItem Text="Check Box 2" Value="2" />
<asp:ListItem Text="Check Box 3" Value="3" />
</asp:CheckBoxList>
<Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
Example codebehind.aspx.cs
btnSubmit.Click += (a, b) =>
{
Page.Validate("vlgSubmit");
if (Page.IsValid) {
// Validation Successful
}
};
There are many other useful feature in Dado.Validators worth a look-see.
https://www.nuget.org/packages/Dado.Validators/
There is a :checked
( http://api.jquery.com/checked-selector/ ) selector you can use :
<script>
$(document).ready(function() {
$(".company input").click(function() {
var cnt = $(".company input:checked").length;
if( cnt == 0)
{
// none checked
$('#CompanyPanel').hide();
}
else
{
// any checked
$('#CompanyPanel').show();
}
});
});
</script>
You may want to add (or use) an id on the container of these checkbox, to optimize selector speed.
As for asp.net messing up client ids on controls, you can use
$('<% =MyControl.ClientID %>')
You can just wait for the click
event on all checkboxes, and perform your validation there. No need for .each()
. This way, you validate whenever any of the checkboxes have been checked or unchecked.
$('input.company:checkbox').click(function(){
if ($('input.company:checkbox:checked').length > 0)
{
$('div#CompanyPanel').show();
}
else
{
$('div#CompanyPanel').hide();
}
});
You can just optimize it a bit as well, and change according to your needs.