I have a form that is pulling in required agreement text from a database and displaying each active agreement clause as a separate checkbox in a repeater. I need to validate that ALL checkboxes in the repeater are checked before the form will submit. Is there a way to do this, or should I go about accomplishing this in a different way than what I have started below?
Currently, I have a CustomValidator, but it only requires that at least one of the checkboxes is checked.
<h1>Agreements</h1>
<asp:Repeater ID="rptAgreements" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top" style="padding:10px;">
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="*" ClientValidationFunction = "ValidateCheckBox"></asp:CustomValidator>
<asp:CheckBox ID="Agreements" value='<%# Eval("AgreementID") %>' runat="server" ClientIDMode="Static" />
</td>
<td style="padding:10px;">
<asp:Label ID="lblAgreementText" runat="server" Text='<%# Eval("AgreementText") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<script type = "text/javascript">
function ValidateCheckBox(sender, args) {
if (document.getElementById("Agreements").checked == true) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
</script>
Code Behind:
try
{
using (SqlConnection con = new SqlConnection(FormConnstring))
{
using (SqlCommand cmd = new SqlCommand("sp_SelectAgreements", con))
{
using (SqlDataAdapter agreeDS = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
agreeDS.Fill(dt);
rptAgreements.DataSource = dt;
rptAgreements.DataBind();
}
}
}
}
You are assigning ClientIDMode="Static" in your code which will generate duplicate Ids in Html and it is not a valid html.
you can assign class for your check boxes and in JS count the agreement check boxes and selected ones then you can compare the numbers. such as bellow:
<input type="checkbox" class="agreement" value="1"> agreement 1
<input type="checkbox" class="agreement" value="2"> agreement 2
<input type="checkbox" class="agreement" value="3"> agreement 3
<input type="checkbox" class="agreement" value="4"> agreement 4
<input type="submit" value="GO" id="btn" />
$('#btn').click(function(){
var chkAll=$('input.agreement').length;
var chkSelected = $('input.agreement:checked').length;
alert(chkAll==chkSelected);
});