PDA

View Full Version : Validation - Check that at least one checkbox is checked


ventura
08-14-2002, 05:57 PM
the code i am using below stops at the checkbox validation even if one is checked. what am i doing wrong?

function validate() {
var str = document.form;

if (str.nameOfHospital.selectedIndex == 0) {
alert("Please select a requesting hospital.");
return false;
}
if ((str.firstName.value == "") || (str.firstName.value == "Enter first name")) {
alert("Please enter patient's first name.");
str.firstName.value = "Enter first name";
str.firstName.focus();
str.firstName.select();
return false;
}
if ((str.lastName.value == "") || (str.lastName.value == "Enter last name")) {
alert("Please enter patient's last name.");
str.lastName.value = "Enter last name";
str.lastName.focus();
str.lastName.select();
return false;
}

// Checks that at least one check box is checked
for (i=0; str.elements[i]; i++) {
var studyTypeText = "Please select at least one study type."

if (str.elements[i].type == "checkbox" && str.elements[i].checked) {
// Move on
}
}


if (str.modality.selectedIndex == 0) {
alert("Please select a modality.");
return false;
}
if ((str.history.value == "") || (str.history.value == "Enter history")) {
alert("Please enter history.");
str.history.value = "Enter history";
str.history.focus();
str.history.select();
return false;
}
}

beetle
08-14-2002, 10:41 PM
Because you are not looping through the options of the checkbox array.var countChecks = 0;
if (str.elements[i].type == "checkbox")
{
for (var j in str.elements[i])
if (j.checked)
countChecks++;
}
if (!countChecks)
{
alert('Select some checkboxes!')
return false;
}Or something close to that (I didn't debug)

Coincidently, my validator (http://www.peterbailey.net/jsdemo) does checkboxes :D