Javascript复选框验证无效

时间:2014-02-19 18:17:20

标签: javascript validation checkbox

如果我在我的javascript“checkboxlimit(document.forms.world.countries [],0)上添加国家[],则javascript无效。如果我删除[]然后复选框验证工作绝对正常。我该如何解决这个问题?这是我的完整代码:

第1页:

<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+" checkboxes")
        this.checked=false
        }
    }
}
}
</script>

<form id="world" name="world" method="post" action="example2.php">
<select name="dropdown" onclick="Calc(world)">
<option value=""></option>
<option value="school">School</option>
<option value="college">College</option>
</select>

<p>Countries:</p>
<input type="checkbox" name="countries[]" value="USA" /> USA<br />
<input type="checkbox" name="countries[]" value="Canada" /> Canada<br />
<input type="checkbox" name="countries[]" value="Japan" /> Japan<br />
<input type="checkbox" name="countries[]" value="China" /> China<br />
<input type="checkbox" name="countries[]" value="France" /> France<br />
<input type="submit" value="Submit">
</form>

<script type="text/javascript">
function Calc(world){
var entersel1 = document.world.dropdown.value;
if (entersel1 == ''){
checkboxlimit(document.forms.world.countries[], 0)
}
else if(entersel1 == 'school'){
checkboxlimit(document.forms.world.countries[], 2)
}
else{
checkboxlimit(document.forms.world.countries[], 3)
}
}
</script>

第2页:

<?php
$dropdown = $_POST['dropdown'];
$countries = implode(',', $_POST['countries']);
echo $dropdown.'<br>'.$countries;
?>

1 个答案:

答案 0 :(得分:0)

<script type="text/javascript">
function Calc(world){
var entersel1 = document.world.dropdown.value;
if (entersel1 == ''){
checkboxlimit(document.forms.world['countries[]'], 0)
}
else if(entersel1 == 'school'){
checkboxlimit(document.forms.world['countries[]'], 2)
}
else{
checkboxlimit(document.forms.world['countries[]'], 3)
}
}
</script>

将它放在括号[]之间,引号之间。