Solved

Java Script to validate a radio button on HTML form.

Posted on 2003-11-12
12
4,082 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
12 Comments
 
LVL 10

Expert Comment

by:NetGroove
ID: 9730786
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
ID: 9730907
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
ID: 9731559
NetGroove

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

NS will throw an error on this and it will not return false, the form will submit anyway.
0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
LVL 10

Expert Comment

by:NetGroove
ID: 9731616
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
ID: 9731635
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
 
LVL 10

Expert Comment

by:NetGroove
ID: 9731641
:)
0
 
LVL 10

Expert Comment

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

Expert Comment

by:NetGroove
ID: 9731690
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
ID: 9731728
>>>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
ID: 9732120
wait until you see my face :)
0
 
LVL 16

Expert Comment

by:jaysolomon
ID: 10353388
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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
This article discusses how to implement server side field validation and display customized error messages to the client.
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…

734 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