asp.net/c# ---how to loop checkbox in a div?
In one of my web page, there are 开发者_高级运维12 checkbox controls in a div tag. I want to make sure the user check at least one checkbox in a div after they submit the form.in one of my asp.net web page. Any idea? I mean server side. I have done client side, but as you know, no one could guarantee all client browser enable javascript.
Since you're using ASP.Net, you may want to consider using the
<asp:CheckboxList />
control, and add an <asp:CustomValidator>
plus validation functions that ensure one checkbox was checked.
While I agree with what others said about the validators, this code does what you want:
int i = 0;
foreach (Control ctl in myForm.FindControl("myDiv").Controls)
{
if (ctl is CheckBox)
{
if (((CheckBox)ctl).Checked)
i++;
}
}
Can you use JQuery? If so, check this out:
Get a list of checked checkboxes in a div using jQuery
Does it have to be is C#? Sounds a lot simplier if you just did it in javascript.
You want to look at the OnClientClick property of the asp:CheckBox control.
Here is an example:
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
In your javascript code (called by the handler) you can loop through all children of the div, looking for checkbox type inputs. jQuery is best for that. You could use something like this:
function countChecked() {
return $("input:checked").length;
}
That function above will return the number of checked checkboxes. After that it's trivial to validate your form. Just remember to return false from the handler called by OnClientClick to avoid a postback (in the event your form doesn't validate).
I just realized you edited your question while I was typing an answer. The above is a client side solution only.
If you just want a server side check for this and dont mind autopostback, give this a try. Just set an event handler for the SelectedIndexChanged event and check to see if an option is selected there. You can then display an error of your choice.
Here is the checkboxlist code:
<asp:CheckBoxList ID="chkBxList" runat="server" AutoPostBack="true"
onselectedindexchanged="chkBxList_SelectedIndexChanged">
<asp:ListItem>option1</asp:ListItem>
<asp:ListItem>option2</asp:ListItem>
<asp:ListItem>option3</asp:ListItem>
</asp:CheckBoxList>
<asp:Label id="lblError" runat="server"></asp:Label>
Codebehind:
protected void chkBxList_SelectedIndexChanged(object sender, EventArgs e)
{
bool oneSelected = false;
foreach (ListItem item in chkBxList.Items)
{
if (item.Selected)
oneSelected = true;
}
if (!oneSelected)
lblError.Text = "Please select an option from the checkbox list.";
else
lblError.Text = "At least one checkbox is selected";
}
Even if the client disables JS this will still make sure they choose at least one.
精彩评论