Reputation: 55
Im trying to validate gender radio buttons. It works if they are not selected, but even when one is selected it still says that "gender is not selected"..does anyone know how to get around this?
I have..
if (!genderMaleRadioButton.checked || !genderFemaleRadioButton.checked) {
errorMessage = errorMessage + "Gender not selected\n";
}
//displays error messages
if (errorMessage) {
alert(errorMessage);
}
//if all information is valid, submission is a success.
else if(!errorMessage) {
alert("Submission successful, thank you " + firstName.value);
}
Upvotes: 0
Views: 40
Reputation: 644
You're using ||
, which means "or". "Or" boolean operator returns true
when at least one of the boolean values is not equal to zero.
It would be more prudent to check if either of them are true just for code clarity (checking for "not nots" can be confusing when dealing with a lot of info. In your case, it doesn't matter much, but imagine a big program which is written in a way that you see the exceptions first and the expected flow always goes last?).
Upvotes: 0
Reputation: 392
You should use &&
if(!genderMaleRadioButton.checked && !genderFemaleRadioButton.checked)
{
errorMessage = errorMessage + "Gender not selected\n";
}
Upvotes: 1
Reputation: 375
You are saying "if the male button is not pressed OR the female button is not pressed, then display the error message." Change the first line to
if(!genderMaleRadioButton.checked && !genderFemaleRadioButton.checked)
,
which makes it say "if the male button is not pressed AND the female button is not pressed, then display the error message."
Upvotes: 2