Link to home
Start Free TrialLog in
Avatar of justmelat
justmelat

asked on

HOw do I use array to capture the names of all my checkboxes to use later in php?

i need to capture the names of the checkboxes a user selects --in an array I am assuming--.  I need to loop thru a function later in the code and apply the respective TYPE OF REQUEST.

I am using the function (attached) to tell me how many boxes were selected.  I use the results to feed my loop so it knows how many times to run.  Each time this loop runs, I want it to spit out the TYPE OF REQUEST.

So maybe first: How do I fill an array with the names of the checkboxes a user selects (If the checkbox is unselected, the name needs to be removed from teh array.)?

Then two, how to do I spit out the contents of that array as i am looping through my function?

Here is the top of my function that I want to run $numberOfRequestTypes times.  So how do I write the array, fill it and then spit it out?

function addToDB()
{
$numberOfRequestTypes= $this->answer['Q_34'];
        for ($count =0; $count <=$numberOfRequestTypes; $count ++ )
        {
           echo $numberOfRequestTypes;
        global $db, $db_conn, $accountId, $requestorId, $projectBrief;
         $requestType = array[];
        if ($this->myDebug)
        {
            $requestId='12345';
        } else
        {
==================FUNCTION===============
 
function totalCheckboxes(theForm)
{
   var totalProjTypes =0;
  //debugger;
  var elements = theForm.elements;
  var total = 0;
  var multiplier=1;
  var imgQty = 0;
  var imgTotal = 0;
  var photoQty = 0
      for(var i=0; i<elements.length; i++)
      {
 
          var element = elements[i];
       
            if(element.type == 'checkbox' && element.checked)
            {
                ++totalProjTypes;
            }
      document.forms.intake.howManyTypes.value = totalProjTypes; 
      //document.getElementById('Q_330').value = total*multiplier;
      //console.log(document.getElementById('Q_330').value);
    }
}
 
 
=============== WEB PAGE CODE==================
<html>
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 2</title>
</head>
 
<body>
 
<form name="myform" id="myform" action="http://thesolutions.com/index.php" method="post" enctype="multipart/form-data">
  <input name="MODE" value="submit" type="hidden"><input name="PAGE" value="INDEX" type="hidden"><input name="NEWPAGE" type="hidden">
  <p><br>
  <script language="javascript">
 
  function checkRequired(clickedButton)
  {
      var f = document.forms.myform; 
      if (isBlank(f.Q_1.value,"Please enter Project Name")) {f.Q_1.focus();  return false;}
      if (isBlank(f.Q_2.value,"Please enter Request Name")) {f.Q_2.focus();  return false;}
      if (isBlank(f.Q_3.value,"Please enter Request Phone")) {f.Q_3.focus();  return false;}
      if (isBlank(f.Q_4.value,"Please enter Email Address")) {f.Q_4.focus();  return false;}
     
       /*if (f.Q_5.selectedIndex==0 )
            {
              alert("Please select Department.");
              f.Q_5.focus();
              return false;
            }*/
            
 
     /* dt1 = getDateObject(document.forms.myform.Q_1.value,"/"); //date submitted
      dt2 = getDateObject(document.forms.myform.Q_18.value,"/"); //due date
      days = (dt2 - dt2);
      var difference = (dt2-dt1);
      
      if (!isDate(f.Q_18.value,"M/d/yyyy"))
      {
        alert("Please provide a valid Final Due Date - mm/dd/yyyy.");
        f.Q_18.focus();
        return false;
      }
      else if(dt1>dt2)        // compare due date with current date
      {
        alert("You can not submit a due date prior to today's date, please change the due date and resubmit.");
        document.forms.myform.Q_18.focus();
        return false;
      }
       else if ( difference < ( 1000 * 60 *60 * 36 ) )
      {
        alert("Due date must be 3 or more business days from date of submission.");
        document.forms.myform.Q_18.focus();
        return false;
      }  */
      
     /* if (f.Q_31.selectedIndex==0 )
            {
              alert("Please select Project Type.");
              f.Q_31.focus();
              return false;
            } */
          
function getDateObject(dateString,dateSeperator)
  {
    //This function return a date object after accepting
    //a date string ans dateseparator as arguments
    var curValue=dateString;
    var sepChar=dateSeperator;
    var curPos=0;
    var cDate,cMonth,cYear;
 
    //extract month portion
    curPos=dateString.indexOf(sepChar);
    cMonth=dateString.substring(0,curPos);
 
    //extract day portion
    endPos=dateString.indexOf(sepChar,curPos+1);
    cDate=dateString.substring(curPos+1,endPos);
 
    //extract year portion
    curPos=endPos;
    endPos=curPos+5;
    cYear=curValue.substring(curPos+1,endPos);
 
    //Create Date Object
    dtObject=new Date(cYear,cMonth,cDate);
    return dtObject;
  }
 
     
      if(clickedButton == 'save')
          goTo('WHOLEBRIEF','update');
      else if(clickedButton == 'submitpending')
          goTo('WHOLEBRIEF','submitpending');
      else
          goTo('THANKYOU','create'); 
  
function isBlank(val,msg)
  {
    if(val==null)
    {
     alert(msg);
     return true;
    }
 
    for(var i=0;i<val.length;i++)
    {
	 if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r"))
     {return false;}
    }
    alert(msg);
    return true;
  }
  }
 
 function checkSelfMail(value, ischecked)
     {
         if (value == "Yes" && ischecked)
         {
            document.getElementById('selfMail').style.display=""; 
         }
         else
          {
              document.getElementById('selfMail').style.display="none";
             
          }
          
     }
  function postcardType(value, ischecked)
     {
         if (value == "Postcards" && ischecked)
         {
            document.getElementById('postcards').style.display=""; 
         }
         else
          {
              document.getElementById('postcards').style.display="none";
             
          }
     }
  function brochureType(value, ischecked)
     {        
          if (value == "Brochure" && ischecked)
         {
            document.getElementById('brochure').style.display=""; 
         }
         else
          {
              document.getElementById('brochure').style.display="none";
          }
     }
  function newsletterType(value, ischecked)
     {        
          if (value == "Newsletter" && ischecked)
         {
            document.getElementById('newsletter').style.display=""; 
         }
         else
          {
              document.getElementById('newsletter').style.display="none";
          }
     }
function deptRosterType(value, ischecked)
     {        
          if (value == "Dept. Roster" && ischecked)
         {
            document.getElementById('deptRoster').style.display=""; 
         }
         else
          {
              document.getElementById('deptRoster').style.display="none";
          }
     }
function annRptType(value, ischecked)
     {        
          if (value == "Annual Report" && ischecked)
         {
            document.getElementById('annRpt').style.display=""; 
         }
         else
          {
              document.getElementById('annRpt').style.display="none";
          }
     } 
         /*var elements = theForm.elements;
             for(var i=0; i<elements.length; i++)
                  {
                      var element = elements[i];
                      
                     if (theType == 'mockUp')
    {
        document.getElementById('style1a').style.display=""
    } else
    {
        document.getElementById('style1a').style.display="none"
    } 
                     if(element.value=="Postcards" && element.checked==true)
                        {
                            alert(element.value +" "+ element.name+" "+element.checked);
                            document.getElementById('postcards').style.display=""; 
                        }
                        else
                      {
                          document.getElementById('postcards').style.display="none";
                         
                      }*/
 
                  //document.getElementById('Q_330').value = total*multiplier;
                  //console.log(document.getElementById('Q_330').value);
                //}
         /*if (value == 'Postcards' && ischecked)
         {
              
              
          }
          else
          {
              document.getElementById('postcards').style.display="none"
             
          }*/
     //}
  function showProjects(val)
  {
  	if(val=='Other')
  		{
     document.getElementById("projType").style.display='';
   }
  	
   if(val=='Banner' || val=='Billboard'|| val=='Brochure'|| val=='Direct Mail'|| val=='Newsletter' || val=='Poster' || val=='Printed Flyer' || val=='Printed Membership Information' || val=='Vehical Wrap' || val=='Translation')
   {
     document.getElementById("projType").style.display='';
   }
   else
   {
    document.getElementById("projType").style.display='none';
   }
  }  
function setShowHide(val,fid)
  {
   if(val=='Yes' || val=='Other')
   {
     document.getElementById(fid).style.display='';
   }
   else
   {
    document.getElementById(fid).style.display='none';
   }
  }
  
function ShowHideGoalOther(val,fid)
  {
   if(val=='Yes' || val=='Other')
   {
     document.getElementById(fid).style.display='';
   }
   else
   {
    document.getElementById(fid).style.display='none';
   }
  }
function ShowHideToneOther(val,fid)
  {
   if(val=='Yes' || val=='Other')
   {
     document.getElementById(fid).style.display='';
   }
   else
   {
    document.getElementById(fid).style.display='none';
   }
  }
    
</script>
  <script language="javascript">
  function addToCompany()
  {
    if(document.forms.myform.Company_TITLE.value=="")
    {
        alert("Please enter value for Company title");
        document.forms.myform.Company_TITLE.focus();
        return false;
    }
    else
    {
        goTo('WHOLEBRIEF','addtoCompany');
    }
  }
</script>
  </p>
  <table style="padding-left: 10px;" border="0" cellpadding="0" cellspacing="0" width="700">
    <tbody>
      <tr>
        <td><!-- Project Overview -->
          <fieldset>
            <legend>Project Overview</legend>
            <table class="myform" border="0" cellpadding="1" cellspacing="1" width="800">
              <tbody>
                <tr>
                  <td colspan="2">
                   <input type="hidden" name="howManyTypes">
                    <p align="right">* indicates required field</p>
                  </td>
                </tr>
                <!-- <tr>
               <td>&nbsp;</td>
              <td> <a href="#" onclick="window.open('getInfo.php','COPY','resize=yes,width=420,height=500,scrollbars=yes')">Copy Data From Previous Request</a>
                  
               </td>
           </tr> -->
                <input name="rtc" type="hidden"><input name="txt_eventType" type="hidden"><!--Request submitted -->
                <tr>
                  <td width="230"><label>Date of Request<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><input name="Q_1" maxlength="10" readonly="readonly" style="background-color: rgb(240, 240, 240);" size="10" value="11/12/2008">
                    <script language="JavaScript">var O_Q_1 = new CalendarPopup();</script>
                    <a class="regular" href="http://thesolutions.com/index.php#" onclick="O_Q_1.select(document.forms[0].Q_1,'anch_Q_1','MM/dd/yyyy'); return false" name="anch_Q_1" id="anch_Q_1"><img src="http://thesolutions.com/images/calendar.gif" align="absmiddle" border="0" width="18" height="22"></a>&nbsp;&nbsp;</td>
                </tr>
                <!--Request By -->
                <tr>
                  <td width="180"><label>Requestor Name<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><input name="Q_2" maxlength="120" size="30" value></td>
                </tr>
                <!--Request Email  -->
                <tr>
                  <td width="180"><label>Requestor Email<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><input name="Q_3" maxlength="120" size="30" value></td>
                </tr>
                <!--phone  -->
                <tr>
                  <td width="180"><label>Extension<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><input name="Q_4" maxlength="120" size="30" value></td>
                </tr>
                <!--Request Type  -->
                <tr>
                  <td width="180"><label>Type of Request</label></td>
                  <td width="520"><input id="Q_41" name="Q_41" onclick="postcardType(this.value, this.checked);totalCheckboxes(this.form);" value="Postcards" type="checkbox">
                    Postcards&nbsp;&nbsp; <input id="Q_42" name="Q_42" onclick="brochureType(this.value, this.checked);totalCheckboxes(this.form);" value="Brochure" type="checkbox">
                    Brochure&nbsp;&nbsp; <input id="Q_43" name="Q_43" onclick="newsletterType(this.value, this.checked);totalCheckboxes(this.form);" value="Newsletter" type="checkbox">
                    Newsletter&nbsp;&nbsp; <input id="Q_44" name="Q_44" onclick="deptRosterType(this.value, this.checked);totalCheckboxes(this.form);" value="Dept. Roster" type="checkbox">
                    Dept. Roster&nbsp;&nbsp; <input id="Q_45" name="Q_45" onclick="annRptType(this.value, this.checked);totalCheckboxes(this.form);" value="Annual Report" type="checkbox">
                    Annual Report&nbsp;&nbsp;</td>
                </tr>
              </tbody>
            </table>
          </fieldset><!--POSTCARDS SECTION-->
          <fieldset id="postcards">
            <legend>Postcards</legend>
            <table class="myform" border="0" cellpadding="1" cellspacing="1" width="800">
              <!--Notes-->
              <tbody>
                <tr>
                  <td width="180"><label>Notes</label></td>
                  <td><textarea name="Q_73" class="regular" rows="4" cols="70"></textarea></td>
                </tr>
                <!-- Indicia-->
                <tr>
                  <td width="180"><label>Indicia<font color="#ff0000"><b>*</b></font></label></td>
                  <td><input name="Q_71" value="Bulk" type="radio"> Bulk &nbsp; <input name="Q_71" value="First Class" type="radio">
                    First Class</td>
                </tr>
                <!-- db provided by client-->
                <tr>
                  <td width="180"><label>Database DB Provided by Client?<font color="#ff0000"><b>*</b></font></label></td>
                  <td><input name="Q_72" value="Yes" type="radio"> Yes &nbsp; <input name="Q_72" value="No" type="radio">
                    No</td>
                </tr>
              </tbody>
            </table>
          </fieldset><!--BROCHURE SECTION-->
          <fieldset id="brochure">
            <legend>Brochure</legend>
            <table class="myform" border="0" cellpadding="1" cellspacing="1" width="800">
              <!-- is this a unit brochure-->
              <tbody>
                <tr>
                  <td width="180"><label>Is this a Unit Brochure?<font color="#ff0000"><b>*</b></font></label></td>
                  <td><input name="Q_74" value="Yes" type="radio"> Yes &nbsp; <input name="Q_74" value="No" type="radio">
                    No</td>
                </tr>
                <!--type of brochure -->
                <tr>
                  <td width="180"><label>Type of Brochure<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_75[]" value="Bifold" type="radio">Bifold</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_75[]" value="Booklet" type="radio">Booklet</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_75[]" value="Quadfold" type="radio">Quadfold</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_75[]" value="Single Panel Insert" type="radio">Single
                    Panel Insert</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_75[]" value="Trifold" type="radio">Trifold</span></td>
                </tr>
                <!-- Self-mailing brochure-->
                <tr>
                  <td width="180"><label>Is This a Self-Mailing Brochure<font color="#ff0000"><b>*</b></font></label></td>
                  <td><input name="Q_76" value="Yes" onclick="checkSelfMail(this.value, this.checked);" type="radio">
                    Yes &nbsp; <input name="Q_76" value="No" onclick="checkSelfMail(this.value, this.checked);" type="radio">
                    No</td>
                </tr>
                <!-- Indicia-->
                <tr id="selfMail" style="display: none;">
                  <td width="180"><label>Indicia<font color="#ff0000"><b>*</b></font></label></td>
                  <td><input name="Q_77" value="Bulk" type="radio"> Bulk &nbsp; <input name="Q_77" value="First Class" type="radio">
                    First Class</td>
                </tr>
                <!--Title of Brochure  -->
                <tr>
                  <td width="180"><label>Title of Brochure (limit of 3-4 words)</label></td>
                  <td width="520"><input name="Q_78" maxlength="120" size="30" value></td>
                </tr>
                <!-- Montage  -->
                <tr>
                  <td><label>Choose Montage<font color="#ff0000"><b>*</b></font></label></td>
                  <td><select name="Q_79[]" class="regular">
                      <option value>Select</option>
                      <option value="ACHE">ACHE</option>
                      <option value="Acupuncture">Acupuncture</option>
                      <option value="Alternatives to Go">Alternatives to Go</option>
                      <option value="Anticoagulation">Anticoagulation</option>
                      <option value="Laboratory Services">Laboratory Services</option>
                      <
                    </select></td>
                </tr>
                <!--Ad Panel  -->
                <tr>
                  <td width="180"><label>Ad Panel</label></td>
                  <td width="520"><input name="Q_80" maxlength="50" size="50" value></td>
                  <!--WEb address  -->
                </tr>
                <tr>
                  <td width="180"><label>Web Address</label></td>
                  <td width="520"><input name="Q_81" maxlength="55" size="35" value></td>
                  <!--Phone number  -->
                </tr>
                <tr>
                  <td width="180"><label>Phone Number</label></td>
                  <td width="520"><input name="Q_82" maxlength="25" size="10" value></td>
                </tr>
                <!--BAck Panel Option -->
                <tr>
                  <td width="180"><label>Back Panel Options<font color="#ff0000"><b>*</b></font></label></td>
                  <td width="520"><span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_83[]" value="Location addresses" type="radio">Location
                    addresses</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_83[]" value="Location addresses with map" type="radio">Location
                    addresses with map</span><br>
                    <span style="white-space: nowrap; background-color: rgb(255, 255, 255);"><input name="Q_83[]" value="Self-Mailer" type="radio">Self-Mailer</span></td>
                </tr>
              </tbody>
            </table>
          </fieldset><fieldset id="newsletter" style="display: none;">
            <legend>N</legend>
            <table class="myform">
              <script>
	function addFile(clickedEl) {
		nodeToCopy = document.getElementById("fileUpload");
		copiedNode = nodeToCopy.cloneNode(true);
		parentNode = document.getElementById("uploadFiles");
		parentNode.insertBefore(copiedNode,clickedEl);
		}
	function removeFile(theFile,fromArray) {
		theForm = document.forms[0];
		theForm["fileToRemove"].value=theFile;
		theForm["arrayToRemove"].value=fromArray;
		theForm.action = "index.php?page="+theForm["page"].value;
		theForm["page"].value = (theForm["page"].value*1)-1;
		if (validatemyformForm(theForm)) theForm.submit();
		}
	</script>
              <tbody>
                <tr>
                  <td valign="top"><label>File upload :</label></td>
                  <td id="uploadFiles" valign="top"><input name="Q_30[]" id="Q_30[]" class="regular" type="file"><br>
                    <input name="fileToRemove" id="fileToRemove" value type="hidden">
                    <input name="arrayToRemove" id="arrayToRemove" value type="hidden">
                    <div id="uploadFileShim" style="display: none;">
                    </div>
                  </td>
                  <td valign="top"><input value="Choose another file" class="boldreg" onclick="addFile(document.getElementById('uploadFileShim'));" type="button"></td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                </tr>
              </tbody>
            </table>
          </fieldset>
          <div style="display: none;" class="template">
            <input name="Q_30[]" id="fileUpload" style="display: block;" class="regular" type="file">
          </div>
        </td>
      </tr>
    </tbody>
  </table>
  <br>
  <p><br>
</form>
 
</body>
 
</html>

Open in new window

Avatar of hielo
hielo
Flag of Wallis and Futuna image

your checkboxes have unique names. So what you need to do is make a list of the names:

$chkNames ="Q_41,Q_42,Q_43,Q_44,Q_45"; 
//convert/cast into an array
$chkNames = exmplode(",",$chkNames); 
//now see which ones you got:
$chkReceived=array();
foreach($chkNames as $chk){
 if( isset($_POST[$chk]) )
 {
   $chkReceived[] = $chk;
 }
} 
print_r($chkReceived);

Open in new window

Avatar of justmelat
justmelat

ASKER

Hielo

should $chkNames  be $chkNames [ ]?
>>should $chkNames  be $chkNames [ ]?
No. I TRIED to "cast/change" that comma-separated list to an array via the "explode" method, BUT I misspelled explode => $chkNames = exmplode(",",$chkNames);

it should be:
$chkNames = explode(",",$chkNames);
Can I change method for a minute?.  I think i figured out and easy way to do this, but of course I can't get it finished

I realized I could just write a query against, my db and get it pull all the requestTypes checked. (table attached)  So I got that done, then I just needed to add the result to the array.  Once that's done, i could get the array to tell me how many records and what the names of the request types are.

The attached works except when I get to the array part, it is only holds the R_NUMBER (in this testing is 5) so here's the question, how to do fill an array with the results of the query, the Q_ID and TEXT field (view attached dataset)
function addToDB()
    {
       global $db, $db_conn, $accountId, $requestorId, $projectBrief; 
        
            $sql  = "Select ANSWER.R_NUMBER, ANSWER.Q_ID, ANSWER.TEXT From ANSWER Where ANSWER.R_NUMBER = 5 And ANSWER.Q_ID IN ('Q_41','Q_42')";
            
            $result=getSQLResult($sql);
 
            while ($row = mysql_fetch_assoc($result) )
            {
                $SV[$row['R_NUMBER']]=$row['R_NUMBER'];
            }
            
            echo $SV;
            return $SV;
        exit;
        

Open in new window

qryDataset.JPG
ok, this works, the array is holding my two values, for this example.  Now how do I count the contents of the array?
function addToRobohead()
    {
       global $db, $db_conn, $accountId, $requestorId, $projectBrief; 
        
            $sql  = "Select ANSWER.R_NUMBER, ANSWER.Q_ID, ANSWER.TEXT From ANSWER Where ANSWER.R_NUMBER = 5 And ANSWER.Q_ID IN ('Q_41','Q_42')";
            
            $result=getSQLResult($sql);
 
            while ($row = mysql_fetch_assoc($result) )
            {
                $SV[$row['R_NUMBER']][$row['TEXT']]=$row['R_NUMBER'];
            }
            $UV=array_unique($SV);
            echo $UV;
            return $UV;
        exit;

Open in new window

I tried adding this to my code:
$numberOFelements = count($UV);

see the screen shots that show the contents of the $UV array and then when I hover over $numberOFelements I just get a value of one (see screen shot also)
array.JPG
numbElements.JPG
>>I realized I could just write a query against, my db and get it pull all the requestTypes checked
OK, but that is NOT what you asked. If I understood you correctly, a user opens your page, checks items Q_41 and Q_43, so you want to know "Out of Q_41...Q_45", which ones were checked. This info would be available upon form submission. Not sure why you are querying the db. What if I click on 41 and 43 now, save. Then come back 3min late and check 44 and 45 only?
The way this app works, the user comes in, fills out the form, checks the correspond boxes, submits the request, all info goes to db.  That what I realize, i didn't really need the array on the main/first page.  The next hour, day, month, the manager will come in and approve/deny the project, that's when this function will run.  The info regarding which request types have been select is already there.  When i realized that, i said i could just query the db, she which request types were there, count them and grab the names, then use that info to run my funtion. Do that make sense?
I wanted to make sure i was correct, so i did just what you said.  I went back into the app, changed selections from 2 to 1.  what the original programmer did was have the app delete the entire request, hold the original number then rewrite it to the db, so for my example, Q_41 was the only value in the db, so when i run my query, it will only find Q_41.
>>. Do that make sense?
Yes.

So you just want the number of times each of those items appear on the db.

            while ($row = mysql_fetch_assoc($result) )
            {
		  	if( !isset( $SV[ $row['Q_ID'] ] ) )
			{
                $SV[ $row['Q_ID'] ]=0;
			}
			++$SV[ $row['Q_ID'] ];
            }

Open in new window

Yes the number of times and the name of the request type which is the TEXT field
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You rock as usual Hielo.  Thanks a bunch!!!!!!!!!!!!!!!!!
you are welcome