请在您想要验证它的任何地方调用以下方法。根据您的实现更改 Checkbox 类名称和 div 名称。
function ValidateCheckBoxCheckedOrNot()
{
var selectedCheckBoxesValue = '';
$('#DIVID').find("input:checkbox.CheckBoxClassName:checked").each(function (i, selected) {
if (selectedCheckBoxesValue.length == 0) {
selectedCheckBoxesValue += $(selected).val();
}
else {
selectedCheckBoxesValue += ',' + $(selected).val();
}});
// Here you also get all the comma separated values if you want else use below method for it
if(selectedCheckBoxesValue.length == 0)
{
alert("Select atleast one checkbox");
}
}
或者您也可以使用以下方式进行操作
function ValidateCheckBoxCheckedOrNot()
{
var selectedCheckBoxes = $('#DIVID').find("input:checkbox.CheckBoxClassName:checked").length;
if(selectedCheckBoxes==0)
{
alert("Select atleast one checkbox");
}
}
编辑后的帖子
<div id="CheckBoxDiv">
<% foreach (var item in Model)
{ %>
<%:Html.CheckBox("EmployeId", new { value = item.EmployeeID,@class="employeeCheckBox"})%>
<span class="field-validation-valid" id="Span1"></span>
<%:Html.LabelForModel(item.EmployeeName)%>
</div>
<%-- <%= Html.CheckBox("Accept", new { @class = "required" })%>
<span class="field-validation-valid" id="Accept_validationMessage"></span>--%>
<%} %>
</div>
<script type="text/javascript">
//Call following method on your button click event.
function ValidateCheckBoxCheckedOrNot()
{
var selectedCheckBoxes = $('#CheckBoxDiv').find("input:checkbox.employeeCheckBox:checked").length;
if(selectedCheckBoxes==0)
{
alert("Select atleast one checkbox");
}
}
</script>