Cho rằng bạn đang buộc người dùng phải check vào 1 trong những checkbox trước khi submit, sau đây là đoạn code snippest giúp bạn làm được điều đó.
Ở đây mình sử dụng thư viện Jquery Validation.
Thêm thư viện:
Chúng ta có thể tải về hoặc include url của thư viện:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
Html makup:
<form id="form1" runat="server">
<div id="chkboxes">
<input type="checkbox" name="bev" value="cream" />With cream<br />
<input type="checkbox" name="bev" value="sugar" />With sugar<br />
<input type="checkbox" name="bev" value="sugar" />With salt<br />
</div>
<div id="msg">
</div>
<input id="btnSubmit" type="submit" value="submit" />
</form>
Đầu tiên mình check xem có bao nhiêu checkbox được check trong sự kiện ready của document
function countChecked() {
var n = $("input:checked").length;
$("#msg").text(n + (n <= 1 ? " is" : " are") + " checked!");
}
Jquery validation cho phép chúng ta thay thế thông điệp lổi khác với message mặc định
$.validator.addMethod('onecheck', function (value, ele) {
return $("input:checked").length >= 1;
}, 'Please Select Atleast One CheckBox')
full code:
<% @ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Using the jQuery Validation Plugin to choose atleast one CheckBox before submitting the Form</title>
<style type="text/css">
label.error, #msg
{
float: none;
color: red;
padding-left: .3em;
vertical-align: top;
}
</style>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$.validator.addMethod('onecheck', function (value, ele) {
return $("input:checked").length >= 1;
}, 'Please Select Atleast One CheckBox')
$(document).ready(function () {
$("#form1").validate({
rules: {
bev: {
onecheck: true
}
},
errorPlacement: function (error, element) {
error.appendTo('#msg');
}
});
countChecked();
$(":checkbox").click(countChecked);
});
function countChecked() {
var n = $("input:checked").length;
$("#msg").text(n + (n <= 1 ? " is" : " are") + " checked!");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="chkboxes">
<input type="checkbox" name="bev" value="cream" />With cream<br />
<input type="checkbox" name="bev" value="sugar" />With sugar<br />
<input type="checkbox" name="bev" value="sugar" />With sugar<br />
</div>
<div id="msg">
</div>
<input id="btnSubmit" type="submit" value="submit" />
</form>
</body>
</html>