简体   繁体   中英

validate checkboxlist in ASP.NET client side

Im trying to validate my checkbox list with the following code, but for some reason it gives me the errormessage every time, even if the right amount of checkboxes are checked, and I cant find any sulotions anywhere, can anyone spot what Im doing wrong?

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

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="validate" ErrorMessage="choose a role, not more than 2"
        ValidationGroup="CreateUserWizard1"></asp:CustomValidator>

    <script type="text/javascript">
    function validate(source, arguments) {
        arguments.IsValid = false;

        var checklist = document.getElementById("CheckBoxList");
        if (checklist == null) return;

        var elements = checklist.getElementsByTagName("INPUT");
        if (elements == null) return;

        var checkBoxCount = 0;
        for (i = 0; i < elements.length; i++) {
            if (elements[i].checked) checkBoxCount++;
        }
        arguments.IsValid = (checkBoxCount > 0 || checkBoxCount <= 2);
    }
</script>

the script is taken from a similar question on stack, and I can't really figure out what "INPUT" relates to?

You must get the rendered id of your check list boxes as:

var checklist = document.getElementById("<%=CheckBoxList.ClientID%>");

you can also read: Accessing control client name and not ID in ASP.NET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM