我有一个复选框组控件,我想让用户检查至少一个盒子,如果他们检查每一个,或3,甚至只检查一个,都无关紧要。
View code
---------
<% foreach (var item in Model)
{ %>
<%:Html.CheckBox("EmployeId", new { value = item.EmployeeID,@class="required"})%>
<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>--%>
<%} %>
</fieldset>
<div class="assign_button">
有人可以帮我一点吗?
答案 0 :(得分:1)
我想要客户验证吗? 如果你使用jQuery,断言这个集合
$('input[type="checkbox"].required:checked');
大于零。
我的意思是这样的:
function validateCheckbox(){
var count = 0;
$('input[type="checkbox"].required:checked').each(function() { ++count; } );
return count > 0;
}
您有按钮<div class="assign_button">
。在这种情况下,您可以写:
$(function(){
$('div.assign_button').click(function(){
if (!validateCheckbox()) {
alert('Please, check something!');
}
else {
alert('You are wonderful!');
}
});
});
答案 1 :(得分:1)
如果您想验证它,请致电以下方法。根据您的实现更改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>