Solved

Java Script to validate a radio button on HTML form.

Posted on 2003-11-12
12
4,074 Views
Last Modified: 2008-03-10
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>
0
Comment
Question by:henrycrinkle34
  • 6
  • 4
12 Comments
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
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>


0
 
LVL 46

Accepted Solution

by:
fritz_the_blank earned 250 total points
Comment Utility
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
0
 
LVL 16

Expert Comment

by:jaysolomon
Comment Utility
NetGroove

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

NS will throw an error on this and it will not return false, the form will submit anyway.
0
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
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>

0
 
LVL 16

Expert Comment

by:jaysolomon
Comment Utility
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>
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
:)
0
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
Take care! We are observed by the Queen :-)
0
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
Hey, did you see that I am the featured Expert of our topic area!
When finally will that gif feature be available?
0
 
LVL 16

Expert Comment

by:jaysolomon
Comment Utility
>>>When finally will that gif feature be available?
what to show your pic?

You have been featured forever.
0
 
LVL 10

Expert Comment

by:NetGroove
Comment Utility
wait until you see my face :)
0
 
LVL 16

Expert Comment

by:jaysolomon
Comment Utility
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
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem to picture file 3 37
HTML page and JavaScript 2 49
jQuery one function to process 3 clicks 7 26
JavaScript error 1 33
Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now