...

View Full Version : Validating Checkboxes



tomyknoker
09-02-2007, 02:55 PM
I have the following JavaScript, I need to edit it to validate and make sure that 1 of 2 checkboxes is selected... The following only checks one...


// Make sure a single checkbox is checked
var boxCheck = false;
if (document.formname.male.checked) {
boxCheck = true; }
if (!boxCheck) {
theMessage = theMessage + "\n --> Agree to the terms";
}

jmrker
09-02-2007, 09:31 PM
Is only one checkbox required to be checked or can both be checked at the same time?
Is it necessary that one of the two (or more) be checked?

If only one necessary in a group, might be better to use a radio button, ie:
o Male o Female o Unknown

If at least one checkbox required then consider (pseudo-code):
...
var maleflag = false;
var femaleflag = false;
var unknownflag = false;
if (male.checked) { maleflag = true; }
if (female.checked) { femaleflag = true; }
if (unknown.checked { unknownflag = true; }
var grpflag = maleflag || femaleflag || unknownflag;
if (grpflag == true) { alert('do TRUE stuff'); } else { alert('do FALSE stuff'); }
...

Alternatively, you could count like this (again pseudo-code):
...
var grpflag = 0;
if (male.checked) { grpflag += 1; }
if (female.checked) { grpflag += 2; }
if (unknown.checked) { grpflag += 4; }
if (grpflag < 2) { alert('male') }
else { if grpflag < 3) { alert('female') } else { alert('HUH?'); }
}
...

grpflag would represent
1 = male
2 = female
3 = what? (male and female)
4 = unknown (might want to check and come back later)
5 = what? (male and unknown)
6 = what? (female and unknown)
7 = what? (male and female and unknown)

Good luck!

PremiumBlend
09-02-2007, 09:56 PM
If this is to check whether the user will "Agree to the terms", you should probably use radio buttons.

tomyknoker
09-03-2007, 02:57 AM
Hi guys... I am working with a JavaScript already and not sure how to add to it from the above...


<SCRIPT LANGUAGE="JavaScript">
<!-- Begin

function validate() {

var theMessage = "Please complete the following: \n-----------------------------------\n";
var noErrors = theMessage

// make sure field is not blank
if (document.form.workphone.value=="") {
theMessage = theMessage + "\n --> Work telephone";
}

// If no errors, submit the form
if (theMessage == noErrors) {
return true;

} else {

// If errors were found, show alert message
alert(theMessage);
return false;
}
}
// End -->
</script>

Basically I need to add a check to make sure that 1 of 5 radio buttons have been pressed, also that 1 of 2 radio buttons been checked and also, that atleast 1 of 3 checkboxes have been checked... Any ideas? I'm kind of stumped...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum