ASP.NET CheckBox Validation Nothing Checked
ASP.NET CheckBox Validation Atleast one Checked
Introduction
In this blog, we will explore a trick to validate whether any CheckBox
inside one CheckBoxList
is checked or not.
Problem
When you define one CheckBoxList
on aspx
page by writing code something like below…
<asp:CheckBoxList RepeatDirection="Horizontal"
ID="chkDemo"
runat="server">
<asp:ListItem Text="Apples" Value="1"></asp:ListItem>
<asp:ListItem Text="Oranges" Value="2"></asp:ListItem>
<asp:ListItem Text="Mangoes" Value="3"></asp:ListItem>
</asp:CheckBoxList>
...it will render on browser like below…
<table id="chkDemo">
<tbody>
<tr>
<td>
<input type="checkbox" value="1" name="chkDemo$0" id="chkDemo_0">
<label for="chkDemo_0">Apples</label>
</td>
<td>
<input type="checkbox" value="2" name="chkDemo$1" id="chkDemo_1">
<label for="chkDemo_1">Oranges</label>
</td>
<td>
<input type="checkbox" value="3" name="chkDemo$2" id="chkDemo_2">
<label for="chkDemo_2">Mangoes</label>
</td>
</tr>
</tbody>
</table>
Basically, it renders number of CheckBoxes
depending on the number of ListItems
inside CheckBoxList
.
So, What Is the Logic Here?
We will call one JavaScript function on a Button Click.
Button would look like…
<asp:Button runat="server" ID="Button1" Text="Submit"
OnClientClick="return validateCheckBoxList();" />
Inside that function, we will run the following logic to validate whether any CheckBox
is checked or not.
- We will find the main
CheckBoxList
first, which is rendered as a Table
.
- Next, we need to find all the
CheckBox
es inside that Table
.
- After that, we have to check if any
CheckBox
is checked by looping through them.
- If any
CheckBox
is checked, then break the Loop and show alert (for demo purpose).
- Return
true
if any CheckBox
is checked, else show alert and return false
.
function validateCheckBoxList() {
var isAnyCheckBoxChecked = false;
var checkBoxes = document.getElementById("chkDemo").getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].type == "checkbox") {
if (checkBoxes[i].checked) {
isAnyCheckBoxChecked = true;
alert("Atleast one CheckBox is checked");
break;
}
}
}
if (!isAnyCheckBoxChecked) {
alert("No CheckBox is Checked.");
}
return isAnyCheckBoxChecked;
}
See the Demo
Here
Note
I have used the CheckBoxList
ID directly, which is chkDemo
. But when your ClientID
changes, you can get the CheckBoxList
like…
document.getElementById("<%= chkDemo.ClientID %>");
Do You Find It Interesting?
Share your thoughts on the blog. Don’t forget to like and share.
CodeProject