...

View Full Version : How to validate a radio button in a form



drumz
01-22-2009, 05:20 AM
I have some code I use for form validation but can't figure out how to make it work for a radio button. The radio button:


<INPUT type="Radio" NAME="BestWayToContact" VALUE='Call Me'>phone
<INPUT type="Radio" NAME="BestWayToContact" VALUE='By Email'>e-mail

Validation code that works for text fields


if ((document.form.phone.value == "Phone Number") ||
(document.form.phone.value == "")) {
missinginfo += "\n - Phone Number";
}
My feeble attempt (I know I need some sort of logic here)


if ((document.form.BestWayToContact.value == "Call Me") ||
(document.form.BestWayToContact.value == "By Email")) {
missinginfo += "\n - Best Way To Contact You";
}

Thanks in advance for your time and help!

rangana
01-22-2009, 05:54 AM
What are you trying to do? It seemed you are not getting the value of the form. Anyway, might help:


var radCon = document.form2.elements['BestWayToContact'];
alert('Best Way to Contact is via: '+(radCon[0].checked?radCon[0].value:radCon[1].value));

drumz
01-22-2009, 06:03 AM
Sorry Rangana but I just gave you a snipet of the script. Here's the whole thing

<SCRIPT LANGUAGE="JavaScript">
function checkFields() {
missinginfo = "";
if ((document.form.realname.value == "Name") ||
(document.form.realname.value == "")) {
missinginfo += "\n - Name";
}
if ((document.form.phone.value == "Phone Number") ||
(document.form.phone.value == "")) {
missinginfo += "\n - Phone Number";
}
if ((document.form.email.value == "") ||
(document.form.email.value.indexOf('@') == -1) ||
(document.form.email.value.indexOf('.') == -1) ||
(document.form.email.value == "E-mail")) {
missinginfo += "\n - E-mail address";
}
if (document.form.Message.value == "") {
missinginfo += "\n - Comments";
}
if (document.form.BestWayToContact.value == "") {
missinginfo += "\n - Best Way To Contact You";
}

if (missinginfo != "") {
missinginfo ="_____________________________\n" +
"You failed to correctly fill in your:\n" +
missinginfo + "\n_____________________________" +
"\nPlease re-enter and submit again!";
alert(missinginfo);
return false;
}
else return true;
}
</script>

Thanks!

rangana
01-22-2009, 06:11 AM
Change this part:


if (document.form.BestWayToContact.value == "") {


...to:


var radCon = document.form.elements['BestWayToContact'];
if (!(radCon[0].checked||radCon[1].checked)) {

drumz
01-22-2009, 06:23 AM
Very nice, thank you very much!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum