You are using || (logical OR). With a pair of radio buttons, one will always be false, and there is no gender[0] or gender[1]. In javascript, names are literal. Even in PHP, with radio button groups, only the value of the checked radio button is passed, that's why they can all have the same name with no []. Unfortunately, when checking the value in javascript, all radios must be evaluated individually (I do this in a loop). In an unrelated matter I just realized that since I changed all the color input names to 'colors[]', that makes their validation a little simpler. But since they no longer occupy the last position in the form, there are other changes to their validation as well.
However, at least in the US, it is generally illegal to require a person to disclose his/her gender unless it is needed, like if you are selling clothing, for male or female styles or sizing. But in a case like that, it should be worded as a preference, not as a declaration of gender, for example:
HTML Code:
Male or Female sizes?
<br>
<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female
You can always ask a person's gender though, it just cannot be required for submission, and therefore should not be validated unless it is a preference, rather than a declaration.
In any case, here's how to validate those two radio buttons using our function (changes and additions, including ones for colors validation, highlighted):
Code:
function validate(f){
f = f.elements;
var msg = '', gender = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'gender' && f[i].checked)
return true;
msg = '\nPlease Check for Male or Female Sizes.';
return false;
}, valid = gender(), colors = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'colors[]' && f[i].checked) ++c;
if (c < 4) msg = '\nPlease Select at least Four Colors.' + msg;
return c > 3;
};
valid = colors()? valid : false;
if(f['city'].options.selectedIndex == 0){
valid = false;
msg = '\nPlease enter City.' + msg;
};
if(f['age'].value == ''){
valid = false;
msg = '\nPlease enter Age.' + msg;
};
if(f['fname'].value == ''){
valid = false;
msg = '\nPlease enter Name.' + msg;
};
if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};
Bookmarks