html多选框checkbox设置选择个数
代码如下,复制可运行:
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>html限制复选框数量title>
head>
<body>
<div>
<form action="" method='post' autocomplete="on" onsubmit="return toVaild()">
<div>
<p><strong>请选择感兴趣的资讯类型:strong>p>
<input value="1" type="checkbox" name="type_1" onclick="return checkCount(this)"/><label>生活label>
<input value="2" type="checkbox" name="type_2" onclick="return checkCount(this)"/><label>睡眠label>
<input value="3" type="checkbox" name="type_3" onclick="return checkCount(this)"/><label>科技label>
<input value="4" type="checkbox" name="type_4" onclick="return checkCount(this)"/><label>历史label>
<input value="5" type="checkbox" name="type_5" onclick="return checkCount(this)"/><label>金融label>
<input value="6" type="checkbox" name="type_6" onclick="return checkCount(this)"/><label>汽车label>
<input value="7" type="checkbox" name="type_7" onclick="return checkCount(this)"/><label>体育label>
<input value="8" type="checkbox" name="type_8" onclick="return checkCount(this)"/><label>工业label>
div>
<button type="reset"><span class="glyphicon glyphicon-remove">取消span>button>
<button type="submit"><span class="glyphicon glyphicon-ok">提交span>button>
form>
div>
<script type="text/javascript">
// 设置只能最多选择三种类型
var checkedCount = 0;
function checkCount(obj) {
if (obj.checked === true) {
if (checkedCount >= 3) {
alert("最多只能选择3种类型哦^_^");
return false;
}
checkedCount++;
} else {
checkedCount--;
}
return true
}
// form提交前验证,最少选择一种资讯类型
function toVaild() {
if (checkedCount === 0) {
alert("请选择至少一种资讯类型哦");
return false;
}
return true;
}
script>
body>
html>
效果如图:
后记
【后记】为了让大家能够轻松学编程,我创建了一个公众号【轻松学编程】,里面有让你快速学会编程的文章,当然也有一些干货提高你的编程水平,也有一些编程项目适合做一些课程设计等课题。
公众号
关注我,我们一起成长~~