0

I have a small javascript function which check validation for checkboxes:

function check_this() {
    var arrCheckboxes = document.create_schedule.elements["username"];
    var checkCount = 0;
    for (var i = 0; i < arrCheckboxes.length; i++) {
        if(arrCheckboxes[i].checked)
        {       checkCount += 1;
        }
    }

        if (checkCount > 0){
                return true;
        } else {
                alert("You do not have any users.");
                return false;
        }

}

Here's the associated Perl code

print "<form action=\"create-plan.cgi\"  method=\"GET\" name=\"create_schedule\" onsubmit=\"return check_this()\">";
        foreach(@these_account_users)
        {       my $test = $_;
                my $choice =1;
                foreach(@all_conf_users)
                {       if ($test =~ $_)
                        {       #print "Duplicate";
                                $choice = 0;
                                last;
                        }

                }
                if ($choice == 1)
                {       print "<input name=\"username\" value=\"$_\" type=\"checkbox\"><b>$_</b><br />";
                }
                else
                {       print "<input name=\"username\" value=\"$_\" type=\"checkbox\" disabled=\"disabled\">$_<br />";
                }

        }


        print '<br /><input name="backup_type" type="submit" value="Select Type">';

        print "</form><br /><br />";

When this is run, it works if no checkbox is selected (i.e the alert is shown). If 2 or more check boxes exist, and atleast one is selected, it accepts it and moves to the next screen. However, if there is only one checkbox and if that is selected, it throws the alert and refuses to move forward.

What am i doing wrong?

EDIT:

On further testing, I find that if there is only one check box, arrCheckboxes.length's value is undefined, however if there are 2 or more accounts, arrCheckboxes.length's value is equal to the exact number of checkboxes. Now I am really stumped.......

4

1 回答 1

0

从您的示例看来,当没有选择任何内容并且只有一个复选框时,它不会返回数组实例。更改 javascript 函数的第一部分,如下所示:

var arrCheckboxes;
if(!document.create_schedule.username.length) {
arrCheckboxes = [document.create_schedule.username];
}
else {
arrCheckboxes = document.create_schedule.elements["username"];
}

这应该可以解决您的错误。

于 2013-11-08T11:09:13.290 回答