所以。基本上,我现在知道如何为选中的复选框添加限制。我还发现了如何通过POST在复选框上的名称中添加"[]"来发送多个值。另一个问题出现了。你是如何把这两者结合起来的?我应该使用什么脚本代码?因为我在下面使用的代码不接受带有"[]"的复选框。这是我的代码:
<script type="text/javascript">
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+" candidates.")
this.checked=false
}
}
}
}
</script>
<body>
<form action="votePage.php" method="post" enctype="multipart/form-data" id="voting" name="voting">
<?php
$limit = 0;
while($limit<3){
?>
<input type='checkbox' name='Candidate' value=<?php echo $limit;?>><?php echo $limit;?> <br>
<?php
$limit++;
}
?>
<input type="submit" name="submit"/>
</form>
<script type="text/javascript">
checkboxlimit(document.forms.voting.Candidate, 2) //this limits checked items to only 2.
</script>
</body>
一个快速的助手将不胜感激。Thnx。
我认为将页面顶部的javascript移到底部会有所帮助。
您可以使用以下语法作为输入元素的名称:
name='Candidate[]'
然后像这样触发CCD_ 1功能:
checkboxlimit(document.forms.voting['Candidate[]'], 2);
您可以将javascript从顶部移动到以下行之前:
checkboxlimit(document.forms.voting.Candidate, 2) //this limits checked items to only 2.
例如:
<form action="votePage.php" method="post" enctype="multipart/form-data" id="voting" name="voting">
<?php
$limit = 0;
while($limit<3){
?>
<input type='checkbox' name='Candidate[]' value=<?php echo $limit;?>><?php echo $limit;?> <br>
<?php
$limit++;
}
?>
<input type="submit" name="submit"/>
</form>
<script type="text/javascript">
function checkboxlimit(checkgroup, 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+" candidates.");
this.checked=false
}
}
}
}
checkboxlimit(document.forms.voting['Candidate[]'], 2); //this limits checked items to only 2.
</script>