Michal Patriak Michal Patriak - 1 year ago 116
HTML Question

Cannot limit number of checkboxes selected (tried multiple snippets)

I have a form that prints out a list of questions stored in the database. The user is supposed to select a maximum of 10 check boxes, but it seems my javascript is being ignored. Am I blanking out on something fundamental to get this to work? I am creating this in a virtual machine with LAMP. I've tried running the code inside Eclipse and in the browser, but nothing happens. Here is my code:

<!DOCTYPE html>
<meta charset="utf-8" />
<title>Question Selection</title>
<script type="text/javascript">
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.questions.questions.length; i++) {
if (docment.questions.questions[i].checked) {
total = total + 1;
if (total > 10) {
alert("Please select only 10 questions");
document.questions.questions[i].checked = false;
return false;
<?php echo "<br />"; ?>
<form id="questions" name="questions" action="GenerateQuiz" method="post">
<table border="2" style="margin:0 auto; padding:5px">
<th>Include in Quiz</th>
$count = 1;
// Print a row for each record in the returned query
foreach($questionList as $key => $row) {
echo "
<td style='text-align:left;'>$row[questionText]</td>
<td style='text-align:center;'><input type='checkbox' name='questions[]' onclick='chkcontrol($count)' value='$row[questionText]' /></td>
<div align="center">
<br />
<input type="submit" value="Take Quiz" />

Answer Source
chkcontrol = function(j) {
    var total = 0;
    var questions = document.getElementsByName('questions[]');
    for (var i = 0; i < questions.length; i++) {
        if (questions[i].checked) {
            total = total + 1;
        if (total > 10) {
            alert("Please select only 10 questions");
            questions[i].checked = false;
            return false;

Is what your chkcontrol function should look like. You do not need jQuery to do this, you were most of the way there!

See a working example here: https://jsfiddle.net/wr58739c/4/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download