Forum Moderators: coopster
<input type="checkbox" name="programs" value="1">
<input type="checkbox" name="programs" value="2">
<input type="checkbox" name="programs" value="3">
<input type="checkbox" name="programs" value="4">
<input type="checkbox" name="programs" value="5">
the user has to check at least one box before submitting the form. so i used some javascript to do the validation.
<script language="JavaScript">
function validateForm()
{
//----------- check check boxes
// set var checkbox_choice to false
var checkbox_choice = false;
// Loop from zero to the one minus the number of radio button selections
for (counter = 0; counter < myForm.programs.length; counter++)
{
// If a radio button has been selected it will return true
// (If not it will return false)
if (myForm.programs[counter].checked)
checkbox_choice = true;
}
if (!checkbox_choice)
{
// If there were no selections made display an alert box
alert("Please select the program(s) you have watched.")
return (false);
}
</javascript>
the validation works fine. but then i am having trouble capturing which checkboxes the user checked and insert that information into the DB.
I understand that a way to capture which checkboxes the user checked is to name the checkbox name like "programs[]" so that php knows to treat it like an array. I tried doing that but my javascript validation function didn't work if i use "programs[]" instead of "programs". Any help would be greatly appreciated. Thanks.
[edited by: someone at 6:12 pm (utc) on Dec. 7, 2004]
skip the js validation and move it to php.
then use the programs[] syntax in the form. The way to test how to create the validation is to view the full data sent by the form when it is posted.
use this to view the data from the form, it will help you understand what is being sent.
echo '<pre>';
print_r($_POST);
echo '</pre>';
<input type="checkbox" name="programs[1]" value="1">
<input type="checkbox" name="programs[2]" value="2">
you should then be able to access info from the programs array after you get the POST data into a variable by using something similar to
foreach($_POST as $key => $value)
{
if(strstr($key,"programs") )//we only want programs
{
$$key=$value;
}
}
you should now have an array variable named $programs that you can check the length of to find out if the user selected a checkbox or not.