1

I am taking a checkbox list in content page of a master page by which i can select multiple values and save in the database. How to confirm that minimum one of the checkboxes r selected at the time of clicking the submit button.

2

2 Answers 2

2

You can do like below.

It does not matter in JavaScript that where control are either or content page or master page

<asp:CheckBoxList ID="chkModuleList"runat="server" />

<asp:CustomValidator runat="server" ID="cvmodulelist"
  ClientValidationFunction="ValidateModuleList"
  ErrorMessage="Please Select Atleast one Module" />

// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
  var chkListModules= document.getElementById ('<%= chkModuleList.ClientID %>');
  var chkListinputs = chkListModules.getElementsByTagName("input");
  for (var i=0;i<chkListinputs .length;i++)
  {
    if (chkListinputs [i].checked)
    {
      args.IsValid = true;
      return;
    }
  }
  args.IsValid = false;
}

Update: Or you can go through this approach: Put any css-class say company. You can go through below.

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
            }
            else
            {
               // any checked
            }
        });
    });
</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 %>')

References:

Sign up to request clarification or add additional context in comments.

Comments

0

Dado.Validators, a library on GitHub, handles this very nicely too.

<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
    }
};

https://www.nuget.org/packages/Dado.Validators/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.