Java Script to validate a radio button on HTML form.

I want to make sure that the radio button has been checked before allowing the form to submit. The form executes ok to the perl script. However it is submitting without the question being answered.

-----------------------------------------------------------------------------------------------------------------
<HTML>
<HEAD>

    <script language="JavaScript">
         function checkForm() {
            if (userResponse.fname.value=='') {
                alert("You must provide a first name");
                event.returnValue=false;
            } else if (userResponse.sname.value=='') {
                      alert("You must provide a surname");
                           event.returnValue=false;
                                }else if (userResponse.trained.value==0)  {
                       alert ("You have not answered Q1");
                       event.returnValue=false;
                                }
      }      
    </script>

</HEAD>

<BODY>

<!-- Use of form -->
<FORM name="userResponse" ACTION="http://kenbane.infc.ulst.ac.uk/~32181502/cgi-bin/thesis/response.pl">

First name:<INPUT TYPE="text" NAME="fname" size="25" VALUE="">

Q1. Have you received any bioinformatics training.
<input type=radio name=trained value=yes>Yes
<input type=radio name=trained value=no>No
<BR><BR>

<!-- Submission & validation -->
<CENTER>
<INPUT type="submit" VALUE="Submit" onclick="checkForm()">
<INPUT TYPE="reset" VALUE="Reset">
</CENTER>
henrycrinkle34Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NetGrooveCommented:
Here my proposal:

<HTML>
<HEAD>
<script language="JavaScript">
function checkForm(theForm) {
  msg = "";
  if (theForm.fname.value=='') {
    msg += "\nYou must provide a first name";
  }
  if (theForm.sname.value=='') {
    msg += "\nYou must provide a sure name";
  }
  qTrain = theForm.trained;
  qCheck = false;
  for(i=0;i<qTrain.length;i++){
    if(qTrain[i].checked==true){
      qCheck = true;
    }
  }
  if (qCheck == false) {
    msg += "\nYou have not answered Q1";
  }
  if (msg>"") {
    alert ("Errors found:"+msg);
    event.returnValue=false;
  }
}    
</script>
</HEAD>

<BODY>

<!-- Use of form -->
<FORM name="userResponse" ACTION="http://kenbane.infc.ulst.ac.uk/~32181502/cgi-bin/thesis/response.pl" onSubmit="return checkForm(this)">

First name:<INPUT TYPE="text" NAME="fname" size="25" VALUE="">

Last name:<INPUT TYPE="text" NAME="sname" size="25" VALUE="">

Q1. Have you received any bioinformatics training.
<input type=radio name=trained value=yes>Yes
<input type=radio name=trained value=no>No
<BR><BR>

<!-- Submission & validation -->
<CENTER>
<INPUT type="submit" VALUE="Submit">
<INPUT TYPE="reset" VALUE="Reset">
</CENTER>
</form>
</body>
</html>


fritz_the_blankCommented:
Here is a script that I wrote to demonstrate how to validate all types of controls:

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT LANGUAGE=javascript>
<!--
//Script courtesy of Patrick Fairfield
//www.FairfieldConsulting.com
function hasText(strFieldName,strMessage){
      var objFormField = document.forms[0].elements[strFieldName];
      var strValue = objFormField.value;
      strValue = strValue.split(" ").join("")
      if(strValue.length<1){
            alert("The value for " + strMessage + " cannot be left blank!");
            objFormField.focus();
            return false;
      }
      return true;
}
//========================================================================
function hasSelection(strFieldName,strMessage){
      var objFormField = document.forms[0].elements[strFieldName];
      if (objFormField.selectedIndex == 0){
            alert("The " + strMessage + " cannot be blank.");
            objFormField.focus() ;
            return false ;
      }
      return true;
}
//========================================================================
function isDate(strFieldName,strMessage){
      var objFormField = document.forms[0].elements[strFieldName];
      strDate = objFormField.value;
      if(strDate.length>0){
               var dateregex=/^[ ]*[0]?(\d{1,2})\/(\d{1,2})\/(\d{4,})[ ]*$/;
                var match=strDate.match(dateregex);
                if (match){
                           var tmpdate=new Date(match[3],parseInt(match[1],10)-1,match[2]);
                     if (tmpdate.getDate()==parseInt(match[2],10) && tmpdate.getFullYear()==parseInt(match[3],10) && (tmpdate.getMonth()+1)==parseInt(match[1],10)){
                        return true;
                        }
                }
            alert("Please enter valid values for the day, month and year for " + strMessage + "!");
            objFormField.focus();
            return false;
      }
      else{
            return true;
      }
}
//========================================================================
function checkRadioControl(strFieldName,strMessage){
      var objFormField = document.forms[0].elements[strFieldName]
      intControlLength = objFormField.length
      bolSelected = false;
      for (i=0;i<intControlLength;i++){
            if(objFormField[i].checked){
                        bolSelected = true;
                        break;
            }
      }      
      if(! bolSelected){
            alert("Please select one option for " + strMessage + "!");
            return false;
      }else{
            return true;
      }
}
//========================================================================
function isEmail(strFieldName,strMessage){
      var objFormField = document.forms[0].elements[strFieldName]
      var strEmail = objFormField.value;
      var bolValid = true;
      if(strEmail.length < 7){
            bolValid = false;
      }
      if(strEmail.lastIndexOf(" ") >0){
            bolValid = false;
      }
      var intLastDot = strEmail.lastIndexOf(".")
      if(intLastDot == -1 ||  strEmail.length - intLastDot >4){
            bolValid = false;
      }
      var intAt = strEmail.lastIndexOf("@")
      if(intAt == -1 ||  strEmail.length - intAt < 5){
            bolValid = false;
      }
      if(!bolValid){
            alert("Please enter a valid email address for " + strMessage + "!");
            objFormField.focus();
      }
      return bolValid;
}
//========================================================================
function validateForm(){
      if(!hasText('txtTest','Test Text')){
            return false;
      }
      if(!isEmail('txtEmail','Test Email')){
            return false;
      }
      if(!hasText('txtDate','Test Date')){
            return false;
      }
      if(!isDate('txtDate','Test Date')){
            return false;
      }
      if(!checkRadioControl('radTest','Test ABC')){
            return false;
      }
      if(!checkRadioControl('chkTest','Test 123')){
            return false;
      }
      if(!hasSelection('selTest','Test Select')){
            return false;
      }
      return true;
}
//-->
</SCRIPT>

</HEAD>
<BODY>
<FORM action="http://www.FairfieldConsulting.com" method=POST  name=form1 onSubmit="return validateForm()">
Test Text<INPUT type="text" id=txtTest name=txtTest><br>
Test Email<INPUT type="text" id=txtEmail name=txtEmail><br>
Test Date<INPUT type="text" id=txtDate name=txtDate><br>
A<INPUT type="radio" id=radTest name=radTest>
B<INPUT type="radio" id=radTest name=radTest>
C<INPUT type="radio" id=radTest name=radTest><br>
1<INPUT type="checkbox" id=chkTest name=chkTest>
2<INPUT type="checkbox" id=chkTest name=chkTest>
3<INPUT type="checkbox" id=chkTest name=chkTest><br>
Test Select<SELECT id=selTest name=selTest>
      <OPTION></OPTION>
      <OPTION>A</OPTION>
      <OPTION>B</OPTION>
</SELECT><br>
<INPUT type="submit" value="Submit" id=submit1 name=submit1>
<INPUT type="reset" value="Reset" id=reset1 name=reset1>
</FORM>
</BODY>
</HTML>

FtB

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jaysolomonCommented:
NetGroove

>>>event.returnValue=false;<<<

NS will throw an error on this and it will not return false, the form will submit anyway.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

NetGrooveCommented:
Thanks jAy.

Here the revised version:
<HTML>
<HEAD>
<script language="JavaScript">
function checkForm(theForm) {
  msg = "";
  if (theForm.fname.value=='') {
    msg += "\nYou must provide a first name";
  }
  if (theForm.sname.value=='') {
    msg += "\nYou must provide a sure name";
  }
  qTrain = theForm.trained;
  qCheck = false;
  for(i=0;i<qTrain.length;i++){
    if(qTrain[i].checked==true){
      qCheck = true;
    }
  }
  if (qCheck == false) {
    msg += "\nYou have not answered Q1";
  }
  if (msg>"") {
    alert ("Errors found:"+msg);
    return false
  }
}    
</script>
</HEAD>

<BODY>

<!-- Use of form -->
<FORM name="userResponse" ACTION="http://kenbane.infc.ulst.ac.uk/~32181502/cgi-bin/thesis/response.pl" onSubmit="return checkForm(this)">

First name:<INPUT TYPE="text" NAME="fname" size="25" VALUE="">

Last name:<INPUT TYPE="text" NAME="sname" size="25" VALUE="">

Q1. Have you received any bioinformatics training.
<input type=radio name=trained value=yes>Yes
<input type=radio name=trained value=no>No
<BR><BR>

<!-- Submission & validation -->
<CENTER>
<INPUT type="submit" VALUE="Submit">
<INPUT TYPE="reset" VALUE="Reset">
</CENTER>
</form>
</body>
</html>

jaysolomonCommented:
Since i already wrote it up i will post anyway.

<HTML>
<HEAD>
<script language="JavaScript">
function checkRadioControl(strFieldName){
      bolSelected = false;
      for (i=0;i<strFieldName.length;i++){
      if(strFieldName[i].checked){
            bolSelected = true;
      break;
      }
}    
      if(!bolSelected){
            return false;
            }
      return true;
}

function checkForm(fObj){
var strErr = "";
  if (fObj["fname"].value == ""){
      strErr += "- First Name\n";
  }
  if(fObj["sname"].value == ""){
     strErr += "- Surname\n";
  }
  if(!checkRadioControl(fObj["trained"])){
     strErr += "- You have not answered Q1\n";
  }
  if(strErr != ""){
       alert("The Following Fields Contain Errors:\n\n"+ strErr);
             return false;
     }
   return true;
}
</script>

</HEAD>

<BODY>

<!-- Use of form -->
<FORM name="userResponse" ACTION="http://kenbane.infc.ulst.ac.uk/~32181502/cgi-bin/thesis/response.pl" onSubmit="return checkForm(this)">

First name:<INPUT TYPE="text" NAME="fname" size="25" VALUE="">
Surname:<INPUT TYPE="text" NAME="sname" size="25" VALUE="">
Q1. Have you received any bioinformatics training.
<input type=radio name=trained value=yes>Yes
<input type=radio name=trained value=no>No
<BR><BR>

<!-- Submission & validation -->
<CENTER>
<INPUT type="submit" VALUE="Submit">
<INPUT TYPE="reset" VALUE="Reset">
</CENTER>
</form>
</body>
</html>
NetGrooveCommented:
:)
NetGrooveCommented:
Take care! We are observed by the Queen :-)
NetGrooveCommented:
Hey, did you see that I am the featured Expert of our topic area!
When finally will that gif feature be available?
jaysolomonCommented:
>>>When finally will that gif feature be available?
what to show your pic?

You have been featured forever.
NetGrooveCommented:
wait until you see my face :)
jaysolomonCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: fritz_the_blank {http:#9730907}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jAy
EE Cleanup Volunteer
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.