Hi everyone,

I have a html form that I want to make sure at least one checkbox in a row of 6 was selected.

I can do this

if (strlen($GradeLevel7) <2){
die("<p align='center'><font face='Arial' size='3' color='#FF0000'>You did not choose a grade level taught.<br>Please use the 'Back' button to correct this entry.</font></p>");
}

to check if one is selected,.

But how do I check to see if any of the 6 are selected?

I don't want to require all, but as many as they need, but at least one is selected.

Note: I have about 12 fields that are required to be filled out. I am using the same approach for the other fields, also. If this is not the most practical way, please let me know.
Thanks in advance,

Don

    Why don't you make the check boxes a group and then simply check the valiue of the group. A value of 0 means no box was checked.

      6 days later

      Hi Subwayman,

      I sort of understand your logic, but do not know how to do that.

      Also, if I make it a group (or array, I assume your reffering to) how would I get the values that are checked?

      It makes sense, but I can not find an example of what you are trying to do.

      Thanks a bunch,

      Don

        To group the checkboxes you just give them an identical name attribute.

        If you'd like them all in an array follow the name with brackets. name='boxCollection[]'

          Don,

          Please ignore my last post. It's not the solution. I think it was late at night and my brain must have been shutting down. Sorry for the confusion.

            Hi mmonaco,

            If I follow you, I currently have

            <input type="checkbox" name="GradeLevel7" value="1" tabindex="6"> 

            for each check box ( GradeLevel8, 9, etc), I should change them all to

            <input type="checkbox" name="GradeLevel[]" value="1" tabindex="6"> 

            ?

            Then on the form that process the results I have:

            $GradeLevel7 = addslashes($_POST['GradeLevel7']);

            . Wouldn't I need to do a loop and change the

            $_POST['GradeLevel[]'}

            ?

            I think I am heading down the correct path, just need some clarification.

            Thanks,

            Don

              Are you using a loop to create these checkboxes?

                You need to give each checkbox a different value so that you can idebtify which ones were clicked on

                
                <input type="checkbox" name="GradeLevel[]" value="1" tabindex="6"> 
                <input type="checkbox" name="GradeLevel[]" value="2" tabindex="7"> 
                <input type="checkbox" name="GradeLevel[]" value="3" tabindex="8">
                
                

                Then you check if any were clicked thus

                
                if (isset($_POST['GradeLevel'])) {
                
                

                  The way you handle a multidimentional array is not by 'nesting' one inside another, you put them in succession. So it would be $POST['gradelevel'][0] $POST['gradelevel'][1] and so on...

                  Now I'm not sure but you may be able to declare your keys in the name attribute. What I mean is:

                  <input type="checkbox" name="GradeLevel[1]" value="1">
                  <input type="checkbox" name="GradeLevel[2]" value="1">
                  <input type="checkbox" name="GradeLevel[3]" value="1">
                  

                  Then to check which are selected:

                  // This will cycle through the array
                  // and put info into $data
                  while ($data = each($_POST['GradeLevel'])) {
                     $data['key'];     // This will return the key of the array (which grade you're checking)
                     $data['value'];  // Returns the value held at the key
                                              // In this case you will be checking to see if the value is equal to 1
                  }
                  

                  Using this info you can make another array containing a list of the keys when the value is equal to 1, or whatever you'd like...

                  !!HOWEVER!!
                  If you cant explicitly assign the keys, then you'll need to use different values.

                  <input type="checkbox" name="GradeLevel[]" value="1">
                  <input type="checkbox" name="GradeLevel[]" value="2">
                  <input type="checkbox" name="GradeLevel[]" value="3">
                  

                  And the PHP equivalent to above would look something like this:

                  foreach ($_POST['GradeLevel'] as $grade) {
                     if (isset($grade)) {
                        $grade; // now this will contain the value from the input
                                      // if you echo ($grade); then it will display a list of the selected grades
                     } 
                  }
                  

                  Please, if someone could verify which or if both of these methods work, let me know. Thank you.

                    The notation - name="GradeLevel[]" results in an array called GradeLevel being posted from the form. The contents of this array will be the values of those checkboxes that were clicked. As I understand it, if no checkboxes are clicked then nothing will be posted, as per any input form element with no value. So you check for it using isset().

                    I may be wrong on this (ain't used it for a while) and it may be that an EMPTY array is posted, in which case isset will be true so you'd have to use array_count_values($POST['GradeLevel']) or count($POST['GradeLevel']) instead.

                    [edit]
                    And a search confirms my thought that isset() will work - but then the other fella may have mislead me as well.

                     if (isset($_POST['GradeLevel'])) {
                       foreach($_POST['GradeLevel'] as $grade) {
                            echo $grade;        // or do with it what you will
                       }
                    }
                    

                      Wow!

                      Those were the best responses I've received in awhile.

                      Thanks, will incorporate those replies into my files (hopefully today or Thursday) and let you know.

                      Thanks all,

                      Don

                        5 days later

                        I read the above suggestions and I can't seem to get it to function correctly. I think I need to show what I am currently doing, because I cannot follow the above suggestions and incorporate them into what I have so far.

                        Here is the code for the Form:

                        <td width="357" height="24">&nbsp; <input type="checkbox" name="GradeLevel7" value="1" tabindex="6"> 
                                                        <font size="2">7th&nbsp; </font> <input type="checkbox" name="GradeLevel8" value="1" tabindex="7"> 
                                                        <font size="2">8th&nbsp; </font> <input type="checkbox" name="GradeLevel9" value="1" tabindex="8"> 
                                                        <font size="2">9th&nbsp; </font> <input type="checkbox" name="Gradelevel10" value="1" tabindex="9"> 
                                                        <font size="2">10th&nbsp; </font> <input type="checkbox" name="GradeLevel11" value="1" tabindex="10"> 
                                                        <font size="2">11th&nbsp; </font> <input type="checkbox" name="GradeLevel12" value="1" tabindex="11"> 
                                                        <font size="2">12th</font></td>
                        

                        And my code for processing the form:

                        // get the data
                        $GradeLevel7 = addslashes($_POST['GradeLevel7']);
                        $GradeLevel8 = addslashes($_POST['GradeLevel8']);
                        $GradeLevel9 = addslashes($_POST['GradeLevel9']);
                        $Gradelevel10 = addslashes($_POST['Gradelevel10']);
                        $GradeLevel11 = addslashes($_POST['GradeLevel11']);
                        $GradeLevel12 = addslashes($_POST['GradeLevel12']);
                        
                        //check and see if Grade 7 was selected  <--- I need to check them all here
                        if (strlen($GradeLevel7) <1)
                        {
                        die("<p align='center'><font face='Arial' size='3' color='#FF0000'>You did not choose a grade level taught.<br>Please use the 'Back' button to correct this entry.</font></p>");
                        }
                        
                        //write out the data to the DB
                        $sql ="insert into Forms";
                        $sql .="(GradeLevel7, GradeLevel8, GradeLevel9, Gradelevel10, GradeLevel11, GradeLevel12,)";
                        $sql .="values('$GradeLevel7', '$GradeLevel8', '$GradeLevel9', '$Gradelevel10', '$GradeLevel11', '$GradeLevel12')";
                        if(!mysql_query($sql)){
                            echo mysql_errno().'<br>'.mysql_error().'<br><br>';
                        }
                        

                        I see know that an array will get all the data, but how do you check to make sure at least one is selected, and if selected, seperate the data to strore in the db?

                        Thanks in advance,

                        Don

                          To incorporate our suggestions you write the html for the checkboxes like this

                          <td width="357" height="24">&nbsp;
                          <font size="2"> 
                          <input type="checkbox" name="GradeLevel[]" value="7" tabindex="6">7th&nbsp;
                          <input type="checkbox" name="GradeLevel[]" value="8" tabindex="7">8th&nbsp;
                          <input type="checkbox" name="GradeLevel[]" value="9" tabindex="8">9th&nbsp;
                          <input type="checkbox" name="Gradelevel[]" value="10" tabindex="9">10th&nbsp;
                          <input type="checkbox" name="GradeLevel[]" value="11" tabindex="10">11th&nbsp;
                          <input type="checkbox" name="GradeLevel[]" value="12" tabindex="11">12th
                          </font>
                          </td>
                          

                          I've cleaned up your html as well: no need for all those font tags cos there is no change from one to the next so you can enclose it all in one set of tags.
                          You should learn to use cascading style sheets for presentation anyway; here are some good tutorials to get you started css tute 1 css tute 2

                          You need to learn to structure your code more clearly for legibility.

                          Now to process the data you just modify the code I already posted.

                            Thanks Roger Ramjet,

                            BTW, I like your screen name, although, I doubt many users understand the origin, at least those under 35 ish!

                            I did what you suggested, and I now get "812" for ex. if they chose the 8th and 12 grades.

                            I currently store a 1 in the Grade7 field, and 1 in Grade8 field etc.

                            How do I take the results, which may not have a character for that field, which may not be sequential, and set a 1 to the correct field? IE set the 8th and 12th grade fields to 1 but put a 0 for the missing fields? Or am I complicating this?

                            Also, you stated my code was not very legible. What part, any suggestions?

                            Thanks,

                            Don

                              How did you print the contents to see the '812'? You should be getting an array return, not a string, so it should be (8,12) not 812. You process that array using foreach(), or any of the other array functions that you find appropriate.

                              As to cleaning up your code, just learn to structure the layout better - although it may just have been this board that screwed your format when you pasted the code in. But always look to reduce keystrokes and elliminate unneccessary code - like enclosing it all in one set of <font> tags as I did instead of the many that you used.
                              Notice that I also put the <td> </td> on seperate lines to the actual content of the cell - 'enclosing' the data. In my code editor I'd also have indented the contents to make the structure even clearer. (but then I can also strip-out whitespace for the production version).

                                Hi RR,

                                I used your code:

                                if (isset($_POST['GradeLevel'])) {
                                   foreach($_POST['GradeLevel'] as $grade) {
                                        echo $grade;        // or do with it what you will
                                   }
                                }
                                

                                Which give me:

                                812

                                Thanks,

                                Don

                                  Which is exactly what it should give you. Perhaps it would become clearer to you what is going on if you changed it to

                                  
                                  if (isset($_POST['GradeLevel'])) {
                                     $i = 1;
                                     foreach($_POST['GradeLevel'] as $grade) {
                                          echo "GradeLevel array element number " . $i . " is " .  $grade . "<br />";
                                          $i++;
                                     }
                                  }
                                  
                                  

                                  Output will then be:

                                  GradeLevel array element number 1 is 8
                                  GradeLevel array element number 2 is 12

                                  I put in the comment '// or do with it what you will' in my original code snippet because that is what I meant, do whatever it is you need to do with the data; 'echo $grade' was just a placeholder to indicate where you should start writing your own code.

                                  
                                  
                                  if (isset($_POST['GradeLevel'])) {
                                     foreach($_POST['GradeLevel'] as $grade) {
                                          // build the string of fields to insert into
                                          $sql_fields .= "GradeLevel" . $grade . ",";
                                          // build your string of values to insert
                                          $sql_values .= "'1',";
                                     }
                                     // then trim the extra comma from the end of each string
                                     $sql_fields = rtrim($sql_fields, ',');
                                     $sql_values = rtrim($sql_values, ',');
                                     // now build your query
                                     $sql = "INSERT INTO Forms (" . $sql_fields . ") VALUES (" . $sql_values . ")";
                                     echo $sql;     // to see the final query string and check the syntax is correct
                                  // now do the rest yourself
                                  
                                  
                                  } else {   // this is where you code what to do if no checkbox was selected
                                      echo 'You must select at least 1 Grade Level';
                                  }
                                  

                                    Hi RR,

                                    I did like you suggested:

                                    if (isset($_POST['GradeLevel'])) {
                                       foreach($_POST['GradeLevel'] as $grade) {
                                            echo $grade;        // or do with it what you will
                                       }
                                    } 
                                    

                                    This gives me the 812, like I posted.

                                    I am not sure why, but I reply'd to this yesterday?? Not sure why it didn't post, but here it is again.

                                    Thanks,

                                    Don

                                      It did post, and I already replied - try reading that reply.

                                        Sorry RR,

                                        I had a senior moment (didn't see the 1,2 for the pages and was posting, again, to your reply on page 2).

                                        I took what you have and played with it:

                                        if (isset($_POST['GradeLevel'])) {
                                           foreach($_POST['GradeLevel'] as $grade) {
                                                // build the string of fields to insert into
                                                $sql_fields .= "GradeLevel" . $grade . ",";
                                                // build your string of values to insert
                                                $sql_values .= 'Grade '.$grade.'<br>';
                                           }
                                           // then trim the extra comma from the end of each string
                                           $sql_fields = rtrim($sql_fields, ',');
                                           $sql_values = rtrim($sql_values, ',');
                                           // now build your query
                                           //$sql = "INSERT INTO Forms (" . $sql_fields . ") VALUES (" . $sql_values . ")";
                                           echo $sql_values;     // to see the final query string and check the syntax is correct
                                        } else {   // this is where you code what to do if no checkbox was selected
                                            die ('You must go back and select at least 1 Grade Level');
                                        } 
                                        

                                        The reason was, they need the value to be Grade 7 for the 7th Grade, etc for each grade.

                                        With that said, I can now get it to display:
                                        Grade 7
                                        Grade 8
                                        Grade 9

                                        for any check box, but I have a sql insert, later in my code for inserting all the data. I do not see how to use what i am doing with the dynamic names array you wrote.

                                        $sql ="insert into Forms";
                                        $sql .="(Title, FirstName, LastName, Position, SubjectTaught, GradeLevel7, GradeLevel8, GradeLevel9, Gradelevel10, GradeLevel11, GradeLevel12, School, SchoolAddress1, SchoolAddress2, City, State, Zip, EmailAddress, Washington, AmericaOne, Greed,  Scaring, Freeloaders, WouldLikeBecause, PlanOnUsing, AverageStudents, VideoUse, Promise, Comments, Date, Time)";
                                        $sql .="values('$Title', '$FirstName', '$LastName', '$Position', '$SubjectTaught', '$GradeLevel7', '$GradeLevel8', '$GradeLevel9', '$GradeLevel10', '$GradeLevel11', '$GradeLevel12', '$School', '$SchoolAddress1', '$SchoolAddress2', '$City', '$State', '$Zip', '$EmailAddress', '$Washington', '$AmericaOne', '$Greed', '$Scaring', '$Freeloaders', '$WouldLikeBecause', '$PlanOnUsing', '$AverageStudents', '$VideoUse', '$Promise', '$Comments', '$Date', '$Time')";
                                        if(!mysql_query($sql)){
                                            echo mysql_errno().'<br>'.mysql_error().'<br><br>';
                                        }
                                        

                                        I know I am close, just stuck on this last part.

                                        Thanks for your patience, hoepfully you have an easy answer,

                                        Don

                                          Write a Reply...