我想限制我的复选框,当我达到限制时,提交button
会显示,
但是,一旦提交button
显示,并且用户已停用其中一个checkbox
,
提交按钮将被禁用。
这是我的代码:
<?php
if (isset($_POST['lol'])){
foreach ($_POST["lol"] as $pastry) {
if ($pastry=="cake") { //make sure the option they chose is part of the options :p
echo "<li>Cake</li>";
}
if ($pastry=="pie") {
echo "<li>Pie</li>";
}
if ($pastry=="cupcakes") {
echo "<li>Cupcakes</li>";
}
if ($pastry=="brownies") {
echo "<li>Brownies</li>";
}
}
}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
/***********************************************
* Limit number of checked checkboxes script- by JavaScript Kit (www.javascriptkit.com)
* This notice must stay intact for usage
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and 100s more
***********************************************/
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick=function(){
var checkedcount=0
for (var i=0; i<checkgroup.length; i++)
checkedcount+=(checkgroup[i].checked)? 1 : 0
if (checkedcount>limit){
alert("You can only select a maximum of "+limit+" checkboxes")
this.checked=false
}
}
}
}
</script>
</head>
<body>
<form action="test.php" id="poll" name="poll" method="post">
<input type="checkbox" id='lol' name="lol[]" value="cake"> Cake :D <br>
<input type="checkbox" id='lol' name="lol[]" value="pie"> Pie <br>
<input type="checkbox" id='lol' name="lol[]" value="cupcakes"> Cupcakes ^O^ <br>
<input type="checkbox" id='lol' name="lol[]" value="brownies"> Brownies :D <br>
<input type="submit" value="Vote">
</form>
<script type="text/javascript">
//Syntax: checkboxlimit(checkbox_reference, limit)
checkboxlimit(document.forms.poll.lol, 2)
</script>
</body>
</html>
答案 0 :(得分:3)
var elems = $('#poll input[type="checkbox"]'),
subm = $('#poll input[type="submit"]').hide();
elems.on('change', function () {
var limit = 2,
_check = elems.filter(':checked').length;
if (_check == limit) {
subm.show();
}else if (_check > limit) {
alert("You can only select a maximum of " + limit + " checkboxes")
this.checked = false;
}else{
subm.hide();
}
});