简体   繁体   中英

Javascript checkbox validation not working

If i add countries[ ] on my javascript "checkboxlimit(document.forms.world.countries[ ], 0)" the javascript is not working. if i remove [ ] then the checkbox validation works absolutely fine. How do i solve this? Here's my full code:

Page 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>

Page 2:

<?php
$dropdown = $_POST['dropdown'];
$countries = implode(',', $_POST['countries']);
echo $dropdown.'<br>'.$countries;
?>
<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>

Put it inside brackets [], between quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM