[Javascript] Checkbox Validation Question

Rodney Myers rodney at aflyingstart.net
Fri Sep 21 08:59:30 CDT 2001


This function check, called onSubmit will work through an array of data CBS
(CheckBoxeS)

The looping is done with the for..in construction to allow for missing questions
in the sequence, during questionnaire development or on revision of the form.

Each array element of CBS is itself an array of checkbox names.
This is not taken for granted.
The loop checks first for the existence of elements
  and then that the element is indeed a checkbox

When a checked checkbox is found, a parallel array called QA (Questions
Answered),
which has each element primed with a false value for each group,
is set true for the group.

A loop through QA provides a list of unanswered questions which is displayed in
alert

A false value is returned to the onSubmit if there are missing responses.


<script language="JavaScript">
var CBS=new Array(); // for element names
var CBG; // to be temp holder of one element of CBS   "Check Box Group"
CBS[1]=["Q1A1","Q1A2","Q1A3","Q1A4","khg"];
CBS[2]=["Q2A1","Q2A2","Q2A3"];
CBS[3]=["Q3A1","Q3A2"];
var QA=new Array(); // for true false - have any boxes been checked in a group

function check(form){
var ret=true; // Return value to onsubmit event handler
var badData=false; // Flag for wrong names and types
for(var i in CBS)
 {
 CBG = CBS[i];
 QA[i]=false; // group response false = nothing checked
              // set true below if checked box is found
 for(var cbi in CBG) // go through check box names
  {
  // check for element's existence and show alert if not there!
  if(form[CBG[cbi]])
   {
   // check that element is a checkbox show alert if not!
    if(form[CBG[cbi]].type=="checkbox")
     {
     if( form[CBG[cbi]].checked ){QA[i]=true;}
     }// checkbox?
    else {alert("Element : form."+CBG[cbi]+" is not a checkbox");badData=true;}
   }// element?
  else {alert("No element : form."+CBG[cbi]);badData=true;}
  }//for
 }

var msg="";
for(var i in QA)
 {if(!QA[i]){msg+="\tQuestion "+i+"\n";ret=false;}}

if(!ret){alert("nothing checked in\n"+msg);}

// If badData you may wish to hold up submit, but this is not implemented

return(ret);
}

</script>


TL Cannon wrote:

> How do I validate a form that has checkboxes (dynamically created) that have
> different names, but are part of the same question group.  I need to see if
> at least one is checked in the group. The ASP scripts require that the
> elements have a different names.
>
> TL
>
>

hth

Rodney

(Contracts welcome!)


--
Shop at ssistant Add-ons and Developer Workshops
http://www.aflyingstart.net/addons/







More information about the Javascript mailing list