Forum Moderators: open
I run a very simple form validation script.
The problem is that I don't know how to request the value of the radio button and make the script work
the code is
function checkForm() {
//alert("called")var e1 = "" ; var e2 = "" ; var e3 = "" ; var e4 = "" ; var e5 = "" ;
var name = document.forms.mainForm.name.value
var email = document.forms.mainForm.email.value
var age = document.forms.mainForm.age.value
var gender = document.forms.mainForm.gender.value
var rides = document.forms.mainForm.rides.value
if (name == "") { e1 = "Name, "}
if (email == "") { e2 = "Email, "}
if (age == "") { e3 = "Age, "}
if (gender == "") { e4 = "Gender, "}
if (rides == "") { e5 = "Rides per week, "}
var theSum = e1+e2+e3+e4+e5
if (theSum!= "") {
alert("You did not complete the following Required Fields:\n" + e1 + e2 + e3 + e4 + e5 +"\n\nPlease Complete this information, then press Submit. Thank You!") ;
return false;
}
}
Vars age, gender and rides are radio buttons.
Only one option on each can be chosen. So it's one value for age, one for gender and one for rides.
I think the problem is with
var age = document.forms.mainForm.age.value where VALUE should be something else.....
I tried changing the script like putting an IF checked, etc..
But it screws the script, it lets the form go though without validation.
Could you please help?
Thanks
var age;
for(i=0;i<document.forms.mainForm.age.length;i++) {
if(document.forms.mainForm.age[i].checked) {
age = document.forms.mainForm.age[i].value;
}
}
var gender;
for(i=0;i<document.forms.mainForm.gender.length;i++) {
if(document.forms.mainForm.gender[i].checked) {
gender = document.forms.mainForm.gender[i].value;
}
}
var rides;
for(i=0;i<document.forms.mainForm.rides.length;i++) {
if(document.forms.mainForm.rides[i].checked) {
rides = document.forms.mainForm.rides[i].value;
}
}
...with the other ones :)
Also, it is important to remember that age, gender, and rides will not return "" if they are not selected. Instead, they will return
undefined.