0

So. Basically I know now how to add a limit to selected check boxes. I also found out how to send multiple values via POST on the checkboxes by adding '[]' to their names. Another problem arises. How do you combine those two? What scriptcode should I use? because the code I used below does not accept checkboxes with '[]'. Here's my code:

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

A quick helper will be greatly appreciated. Thnx.

Alex Andrei
  • 7,315
  • 3
  • 28
  • 42

1 Answers1

0

I think it will help to move your javascript that is on top to the bottom of the page.

You can use this syntax for the name of the input element:

name='Candidate[]'

and then trigger the checkboxlimit function like this:

checkboxlimit(document.forms.voting['Candidate[]'], 2);

You can move your javascript from the top before this line:

checkboxlimit(document.forms.voting.Candidate, 2) //this limits checked items to only 2.

For example:

<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>
The fourth bird
  • 154,723
  • 16
  • 55
  • 70