Page 1 of 1

Solve me Please!

Posted: Fri Aug 15, 2008 6:36 am
by skinbug
Hi, I have a registration form that returns the errors to the user when they make a mistake, ie, they don't then have to re-type the data.

This works for the text fields, but i can't get it to work for the checkboxes. Here is some of the code as an example...

form.php

Code: Select all

 
<input type="text" name="mobile" value="<?php echo $form->value("mobile"); ?>" />
 
<lable><input type="checkbox" name="optional[]" value="chk1" />Box 1</label>
<lable><input type="checkbox" name="optional[]" value="chk2" />Box 2</label>
<lable><input type="checkbox" name="optional[]" value="chk3" />Box 3</label>
 
With the 'mobile' text field, the php points to a function value() listed below, which echoes back the value entered to the name of the field, ie, mobile.

process.php

Code: Select all

 
function value($field) {
   if(array_key_exists($field, $this->values)) {
      return htmlspecialchars(stripslashes($this->values[$field]));
   }
   else {
      return "";
   }
}
 
I have tried the same thing with the checkboxes, but to no success. The problem is that the checkboxes all have the name of 'optional', so if the user checks one of them, and there is an error elsewhere in the form, it is returned to them but the script checks any box with the name of optional, which is all of them!! See below...

Code: Select all

 
<input type="checkbox" name="optional[]" value="chk1" <?php if($form->value("optional") !=""){ echo "checked == 'checked'"; } ?> />
 
I can't find the solution to this anywhere on google as everything I type about returning form values or storing form data comes up with hits about databases, which is not what I'm looking for.

I have also tried many variations of the code above with no success...can anyone please help?

Re: Solve me Please!

Posted: Fri Aug 15, 2008 6:59 am
by onion2k
optional will be an array of values. You need to check if the value for the specific checkbox is in the array that came from the user. Eg

Code: Select all

if (in_array("chk1", $_POST['optional'])) { echo "checkbox 1 was checked"; }

Re: Solve me Please!

Posted: Fri Aug 15, 2008 8:54 am
by skinbug
Yeh, I've tried this exact thing and it outputs on the screen with a warning next to each checkbox...

Warning: in_array() [function.in_array]: Wrong datatype for second argument in C:\wamp\www\...

Though this is the most logical way of doing it, I have also seen examples of this. The difference is in the examples, the array is declared and put into a variable, eg,

$array = array(1,2,3,...)

then the $array is used as the second argument, not $_POST['optional']

I am not declaring the array, as the checkboxes may change in the future, and it is not know what the array will consist of...is this where my error is??

Re: Solve me Please!

Posted: Fri Aug 15, 2008 8:58 pm
by andre_c
Also keep in mind that if none of the checkboxes are checked, the $_POST['optional'] variable will NOT be set