html多选框checkbox设置选择个数
代码如下,复制可运行:
<!DOCTYPE html>
<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">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<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>
效果如图: