Form Validation on RadioButtons & Check boxes

Is it possible to perform form validation on RadioButtons and Checkboxes?

I have a form that already uses two form validations to verify textfield input and drop down box input -- if it's possible to perform form validation on RadioButtons & CheckBoxes could they be added to the previous onSubmit checking using concatenation (like the two now)?

Thanks,

mapper
mapperAsked:
Who is Participating?
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.

bbangerterCommented:
It depends on what your current code looks like for how to add them to your existing function, but yes you can do validation and checking on them.

For radio buttons the syntax to check whether a particular radio button is the one selected would be

document.FormName.radioButtonName[n].checked

Where n is the nth selection in the radio buttons starting with 0.  This would return true if that button is selected.

Checking check boxes is very similar

document.FormName.checkBoxName.checked

From there you can get the value of either of them with
document.FormName.radioButtonName[n].value or document.FormName.checkBoxName.value
respectively.
0
oubelkasCommented:
Here, a complete form validation :

<html>
<head>
<title> check form </title>
<script language="javascript">
<!--
function checkAllValues(myForm){
  if (!myForm.myCheckbox.checked){
     alert('Check this!');
     myForm.myCheckbox.focus();
     return (false);
  }
  if (!myForm.myRadio.checked){
     alert('Check this radio button too!!');
     myForm.myRadio.focus();
     return (false);
  }
  if (myForm.mySelect.options[0].selected == true ) {
    alert ('Select something!');
    myForm.mySelect.focus();
    return (false);
  }
  if (myForm.myInput.value == ""){
    alert ('Put something in the textarea!');
    myForm.myInput.focus();
    return (false);
  }
 return (true);
}
// -->
</script>
</head>

<body>
<table border="0">
<form name="myForm" method="get" onSubmit="return checkAllValues(this)" >
    <tr>
     <td valign="top" align="right"><b>Check this<b></td>
     <td valign="top" align="left"><input type="checkbox" name="myCheckbox" value="1"></td>
   </tr>
    <tr>
     <td valign="top" align="right"><b>Check this<b></td>
     <td valign="top" align="left"><input type="radio" name="myRadio" value="1"></td>
    </tr>
         
    <tr>
      <td valign="top" align="right"><b>Select something </b></td>
      <td valign="top" align="left"><select name="mySelect">
        <option value="">
        <option value="one"> one...
        <option value="two"> or pick two
        <option value="three"> or maybe three
      </select></td>
   </tr>
   <tr>
      <td valign="top" align="right"><b>Put something here!</b></td>
      <td valign="top" align="left"><textarea name="myInput" rows="6" cols="55"></textarea></td>
   </tr>
   <tr>
     <td></td><td>
       <input type="submit" name="mySubmit" value="check it">
       <input type="reset" name="myReset" value="Reset">
     </td>
   </tr>
</form>
</table>
</body>
</html>

Hope this will work out for you

Joseph
0
mapperAuthor Commented:
Dudes,

I guess I did not explain the problem well enough (my fault!).

The form is very, very large and only some of the fields are required.  The form is for requesting web shares (for the company I work for) and the SA's use the form input (that has an ASP backend to harvest the data and then e-mail to the right SA) to process the request.  The validation enures that the required information is present.  Currently,  I have reused form validation script from previous request forms, but this time the formlady wants to morph the form to add the radiobuttons and checkboxes (she likes the way the look better!).  The existing validation scripts are tied to trigger off of the onSubmit click event.  I use one validation script for the textfield inputs and it pops up a warning that allows the user to type in the missing information.  The other script is for the drop down boxes it throws up a warning indicating the required drop down box that was missed (where it is on the form - the user scrolls back up to the required drop down box and makes the appropriate selection) -- It appears from the example provided that I will have to add the code for the check boxes (they can have multiple checks but must have at least one item checked - so the code needs to check to see if at least one box is checked) in a seperate script entry and then add it to the onClick event:

<INPUT onClick="return(checkform() && validate());" type="submit" name="Submit" value="Submit Form">

Basically, the radiobutton script only needs to make sure that one button has been selected -- I am guessing that seperate script will be added and then added to the onClick event.

I can not go back and make it one validation the form is way too big and it would take to long -- I am just looking for the two extra pieces that I can add and then add to the onClick event.

Thanks,

mapper
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

brigmarCommented:
To check at least one radio button in a group has been selected...

where rg = the radio group:

for(i=0,j=0; i<rg.length; i++) {
 if(rg[i].checked) {
  j++;
 }
}
if (!j) {
 rg[0].focus();
 alert("one of the radio buttons must be selected");
}


To check checkboxes have been set is a little more difficult, as they dont, by default have a logical grouping.

One way is to name all the checkboxes in a group identically, in which case, you can access them via an array (identical to the radio boxes). This will return a comma separated list at the server side for the checkboxes.

Brian
0
freshmeatCommented:
i agree with brigmar
u can name those checkboxes as "check1, check2..."
actualy, in asp code, u can name them as "...check<%=i%>"
0
punkerCommented:
You can always do:

<INPUT TYPE="hidden" name="myfield_Required" value="myfield is required, please enter a value for it.">

It's not as fancy as JavaScript validation, nor anywhere near as robust, but it will do the job. If I have one or two fields that are required in a form, chances are instead of writing a bunch of JavaScript, I'll stick in a hidden required field. I like them especially because they are not only more simple (in my mind), but because they work on any browser, no JavaScript is required.

The main drawback is that it does the validation WHILE the form is being processed, and not BEFORE like a validation script would, which means the user gets a page that says, "Your form was not submitted due to the following reasons: etc." (then they must press the back button and fix the problems) and not an alert that pops up when the user clicks submit and says, "Please fill out this field!"

Anyhow, that's my two pence.

0
mapperAuthor Commented:
The radiobuttons I am not so concerned about any longer.  I got the formlady to agree to change them to drop down boxes. However, there is one group of checkboxes that she needs to have validated:

Application
<input type="checkbox" name="AppReqSpace" value="Application"><br>
        Dynamic Web
<input type="checkbox" name="AppReqSpace" value="Dynamic Web"><br>
        Database&nbsp;
<input type="checkbox" name="AppReqSpace" value="Database">

This is the one group of checkboxes that does need to be validated the others can be changed to drop downs...

Thanks,

Mapper
0
brigmarCommented:
Mapper,

You can use the same code as for groups of radiobuttons, as I displayed earlier
...

Using your examples..


<INPUT onClick="return(checkform() && validate() && checkradio(this.form.checkbox));" type="submit" name="Submit" value="Submit Form">

where :

function checkradio(o) {
 for(var i=0; i<o.length; i++) {
  if(o[i].checked) {
   return true;
  }
 }
 return false;
}


The checkradio function works on both radiogroups and checkboxes that have a common name (like you have).

Brian
0
mapperAuthor Commented:
brigmar,

So, would I change the function name to reflect the common name of the radiobutton/checkbox group?

Like:  

function checkradio(AppReqSpace) {
 for(var i=0; i<AppReqSpace.length; i++) {
    if(AppReqSpace[i].checked) {
      return true;
     }
  }
return false;
 }

That part is a little confusing to me how would I differentiate that?

Also,  if formlady decides to make another group of check boxes required...  How would I modify the script to include that?

Thanks,

Mapper
0
brigmarCommented:
Nope...

checkradio() is a function
use it as I supplied...

within the function, we work with "o" which is the local reference to the object we passed as an argument...

the changes would be made in the calling of the function:

<INPUT onClick="return(checkform() && validate() && checkradio(this.form.AppReqSpace));" type="submit" name="Submit" value="Submit Form">

The function works with *BOTH* checkboxes of identical names, and radiobuttons.

eg... if I had a group of radio buttons under the name "myradio", then I would extend the call onclick handler thus:

<INPUT onClick="return(checkform() && validate() && checkradio(this.form.AppReqSpace) && checkradio( this.form.myradio ) );" type="submit" name="Submit" value="Submit Form">


Is that clearer ?

Brian
0
mapperAuthor Commented:
Brain,

Got cha, but what happens if formlady wants to add another set of checkboxes... I have ensured that all of the checkboxes on the form (the ones grouped together) have the same name.  My real problem here is...

How do I modify the script to cover more than one group of check boxes?  This script appears to address just the one set...

This script go into the header:

<SCRIPT language='javascript'>
<!--
function checkradio(AppReqSpace) {
                       for(var i=0; i<AppReqSpace.length; i++) {
                          if(AppReqSpace[i].checked) {
                            return true;
                           }
                        }
                      return false;
                       }

//-->

</script>

How would it be modified to add other checkboxes though?  That's what is reall confusing me.  I see how to make the mods to the onClick of the submit button -- basically, change to resemble the others...

Would you need the names of the other check boxes?

Thanks,

Mapper
0
brigmarCommented:
Add the checkboxes in groups...

...and you've changed the function

leave it as:

function checkradio(o) {
 for(var i=0; i<o.length; i++) {
  if(o[i].checked) {
   return true;
  }
 }
 return false;
}

If you want to add another group of checkboxes, called "vegetables", then your onclick handler would be..

<INPUT onClick="return(checkform() && validate() && checkradio(this.form.AppReqSpace) && checkradio( this.form.vegetables ) );" type="submit" name="Submit" value="Submit Form">

All you're doing is calling the function with a different argument.

This is what functions are used for...

Brian
0
mapperAuthor Commented:
Brian,

Cool beans...

However, where do I stick the function?  I thought it had to go in the header somewhere?

Thanks,

mapper
0
brigmarCommented:
<html>
 <head>
 <script language="javascript"> <!--
 // The javascript goes in here...

 function checkradio(o) {
 for(var i=0; i<o.length; i++) {
  if(o[i].checked) {
   return true;
  }
 }
 return false;
}

 // -->
 </head>
 <body>
 body stuff goes here
 </body>
</html>
0
mapperAuthor Commented:
Brain,

Brain fart!  I know what was eating at me...

The validation needs to throw an alert!  So, it draws the users attention to the missing checkbox (in this case) and alerts them that the a check box in the group requires a selection... That's what I was trying to say in a round about way...

Thanks,

mapper
0
brigmarCommented:
Change the checkradio function to...

function checkradio(o) {
 for(var i=0; i<o.length; i++) {
  if(o[i].checked) {
   return true;
  }
 }
 o[0].focus();
 alert("At least one choice must be made.");
 return false;
}

This will move the input focus to the first radio button/checkbox in the group, and display an alert...

Brian
0
mapperAuthor Commented:
Brian,

A stupid question but, will changing checkradio(o) to checkbox(o) screw up anything?

Thanks,

mapper

0
brigmarCommented:
. as long as you change ALL references to the function, you should be okay

Brian
0
mapperAuthor Commented:
Brian,

Sheesh, I feel stupid -- I am not looking at what you are sending very thoroughly -- What I am trying to get at is...

The alert needs to direct the user to the specific group of checkboxes they overlooked -- this form is very large and formlady wants all the validations to spell out where the user needs to go back and provide the missing required info..

thanks,

mapper
0
brigmarCommented:
the code I provided *WILL* direct the user to the first checkbox/radiobutton in the group that has the error.

"o[0].focus();" achieves this

Brian
0
mapperAuthor Commented:
Brian,

SCHWEEEET!  I almost choked on my cheesie poofs!!

Let me pluger in and I will repond with I'm a dumb ass or award the points!

Thanks,

mapper
0
brigmarCommented:
LOL..
you *WILL* respect my authoritay
*grin*

Brian
0
mapperAuthor Commented:
Dude,

Why does it work like this? Formlady drops a crap load of mods to the "Mother of all forms" and I have to hack and whack on the other validation scripts - because she wants to cut a bunch of the required fields out... It's Friday and I was hoping to work on the checkbox thing...

Oh well, all I know is; "Drugs are bad, umkay"

mapper
0
mapperAuthor Commented:
Brian,

It did not work...

Here is how I tried to implement it:

<script language="javascript"> <!--
   // The javascript goes in here...

   function checkbox(o) {
     for(var i=0; i<o.length; i++) {
       if(o[i].checked) {
          return true;
          }
     }
     return false;
   }

// -->
</script>

Submit button:

<INPUT onClick="return(checkform() && validate() && checkbox(this.form.AppReqSpace) && checkbox(this.form.AIAppType));" type="submit" name="Submit" value="Submit Form">

I only have two groups of check boxes that need to be required here is the HTML for those:

          <INPUT type="checkbox" name="AppReqSpace" value="Application">
          <BR>
          Dynamic Web
          <INPUT type="checkbox" name="AppReqSpace"
                    value="Dynamic Web">
          <BR>
          Database&nbsp;
          <INPUT type="checkbox" name="AppReqSpace"
                    value="Database">

AND

      <TD valign=top width="419" align="right" height="58"> <font color="#0000FF"><BR>
        Mission-Critical, Multi-tasking; A
        <INPUT type="radio" name="AIAppType" value="Mission-Critical, Multi-tasking; A">
        <BR>
        Mission-Critical, Single-tasking; B
        <INPUT type="radio" name="AIAppType" value="Mission-Critical, Single-tasking; B">
        <BR>
        Non-Critical Multi-tasking; C
        <INPUT type="radio" name="AIAppType" value="Non-Critical Multi-tasking; C">
        <BR>
        Non-Critical Single-tasking; D
        <INPUT type="radio" name="AIAppType" value="Non-Critical Single-tasking; D">
        <BR>
        Unknown
        <INPUT type="radio" name="AIAppType" value="Unknown">
        </font></TD>


It needs to work on Netscape/IE 4.0 or higher...

Thanks,

map
0
brigmarCommented:
what doesn't work ??

if it's not returning an alert box, it's because you havent implemented that code in the function...

Brian
0
mapperAuthor Commented:
Brian,

DUH! I am a rock!

<script language="javascript"> <!--
   // The javascript goes in here...

   function checkbox(o) {
     for(var i=0; i<o.length; i++) {
       if(o[i].checked) {
          return true;
          }
     }
   o[0].focus();
     alert("At least one choice must be made.");
   return false;
   }

// -->
</script>

I added the alert, tried it again and nothing...  The two groups of check boxes had nothing checked and no alert was popped up and the focus on the first group of checkboxes did not happen either...

Thanks,

mapper
0
brigmarCommented:
can u possibly post the entire page, as is ?
0
mapperAuthor Commented:
Brian,

It's behind a firewall -- but, if you provide an e-mail address I could shoot it to you...

mapper
0
brigmarCommented:
. it's on my profile :)

Brian
0
mapperAuthor Commented:
Brigmar,

It's on the way -- I see now from reading your profile again -- London -- so excuse the dumb question...

mapper
0
mapperAuthor Commented:
I could never get Brigmar's solution to work.  I have submitted the HTML page to Brigmar and have never heard back from him with a working solution.

The question has been adequately defined with follow up comments - I would like a working solution for validating checkboxes and radio buttons.

Thanks,

Mapper
0
brigmarCommented:
My apologies Mark,

I've been away with my Fiancee for a while, and now a deadline at work.

Still, looking at your HTML, I can tell you what is wrong...

You claim to have the following code :

<INPUT type="checkbox" name="AppReqSpace" value="Application">
<BR>
Dynamic Web
<INPUT type="checkbox" name="AppReqSpace" value="Dynamic Web">
<BR>
Database&nbsp;
<INPUT type="checkbox" name="AppReqSpace" value="Database">

but the code was actually :

<INPUT type="checkbox" name="AppReqSpaceApp" value="Application">
<BR>
Dynamic Web
<INPUT type="checkbox" name="AppReqSpaceDyn" value="Dynamic Web">
<BR>
Database&nbsp; </FONT>
<INPUT type="checkbox" name="AppReqSpaceDB" value="Database">

i.e., the checkboxes have different names. My first comment to the thread:

"One way is to name all the checkboxes in a group identically, in which case, you can access them via an array (identical to the radio boxes). "

I just checked the form, and it fires the alert box..

Brian
0
mapperAuthor Commented:
Brain,

You were right about the name snafu -- I did not change the name to be unique to all three checkboxes.  However, I did just change and added this to the submit button:

<INPUT onClick="return(checkform() && validate() && checkradio(this.form.AppReqSpace));" type="submit" name="Submit" value="Submit Form">

and tried it and it walks through the first two form valdations and then nothing...

I have this as the code for the checkbox validation:

<SCRIPT LANGUAGE="JavaScript">

<!--

function checkradio(o) {
   for(var i=0; i<o.length; i++) {
      if(o[i].checked) {
         return true;
          }
      }
      o[0].focus();
      alert("At least one choice must be made.");
      return false;
   }

//-->

</SCRIPT>


I am sorry about the change is questions status -- but, I was starting to get edgy about not hearing from you for so long...

Thanks,

Mapper
0
brigmarCommented:
Mark,

What you're seeing is because of this logic:

<INPUT onClick="return(checkform() && validate() && checkradio(this.form.AppReqSpace));" type="submit" name="Submit" value="Submit Form">

It is returning the logical AND of the three validation functions.

It evaluates the expression left to right, and when validate() returns false, it does not NEED to call checkradio() to evaluate the expression.

Comply with all the other field requirements and try again. It fires.

Add this javascript function...

function doValidate(f) {
 var v1 = checkform();
 var v2 = validate();
 var v3 = checkradio(f.AppReqSpace);
 return v1 && v2 && v3;
}

and change the submit button to...

<INPUT onClick="return doValidate(this.form);" type="submit" name="Submit" value="Submit Form">

This will evaluate each function, and then apply the logic later.

Brian
 
0
mapperAuthor Commented:
Brain,

Now that you explain the logic of it -- I see what you mean! I made sure that the required fields were taken care of and bam!  the alert popped up...  I did not see that the other validations returning a false would not let the check box validation work.

I appreciate your patience with me and re-submit your comment in the form of a question and I will gladly award you the points!  You really deserve them...

Thanks,

Mapper
0
brigmarCommented:
Mapper,

You can use the same code as for groups of radiobuttons, as I displayed earlier
....

Using your examples..

Change the submit button to...

<INPUT onClick="return doValidate(this.form);" type="submit" name="Submit" value="Submit Form">

where :

function doValidate(f) {
 var v1 = checkform();
 var v2 = validate();
 var v3 = checkradio(f.AppReqSpace);
 return v1 && v2 && v3;
}

function checkradio(o) {
 for(var i=0; i<o.length; i++) {
  if(o[i].checked) {
   return true;
  }
 }
 return false;
}


The checkradio function works on both radiogroups and checkboxes that have a common name (like you have).

Brian
0

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
mapperAuthor Commented:
Brian,

Your patience with me was nothing short of outstanding!

I bumped up the points because you definitely deserve them!

Thanks again,

Mapper
0
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.