Let's analyze...
When
CheckBoxList
is rendered in
Browser, it will be a
Table having many
CheckBox
inside one one
td
like...
<table class="horizontalListbox" id="Listbox_Permission">
<tbody>
<tr>
<td>
<input type="checkbox" value="1" name="Listbox_Permission$0" id="Listbox_Permission_0">
<label for="Listbox_Permission_0">Apples</label>
</td>
<td>
<input type="checkbox" value="2" name="Listbox_Permission$1" id="Listbox_Permission_1">
<label for="Listbox_Permission_1">Oranges</label>
</td>
<td>
<input type="checkbox" value="3" name="Listbox_Permission$2" id="Listbox_Permission_2">
<label for="Listbox_Permission_2">Mangoes</label>
</td>
</tr>
</tbody>
</table>
Now, let's add
OnClientClick
attribute to the
Button to call a
JavaScript
function...
<asp:Button runat="server" ID="Button1" Text="Submit" OnClick="OnButton1_Click" OnClientClick="return someJavaScriptFunction();" />
After that, it will render as...
<input type="submit" id="Button1" onclick="return someJavaScriptFunction();" value="Submit" name="Button1">
So, what's Next?
In that function, we will just try to fetch all the
CheckBoxes
and try to loop through each of them to see if anyone is
checked
or not. If
checked
, we will return
true
and show one
alert
.
function someJavaScriptFunction() {
var isAnyCheckBoxChecked = false;
var checkBoxes = document.getElementById("Listbox_Permission").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;
}
Please read the
Comments inside code to know what is happening inside it.
Demo
Check the Demo. See how it is working. Customize it according to your requirements.
[Demo] CheckBoxList Validation in ASP.NET[
^]