0

I am dynamically creating forms based on values in a database. Each form element corresponds to a specific database entry, which includes the name, label, type, and (depending upon the type) possible values to be displayed with the form element.

The name value for each form element is set to the identity column value of the corresponding database entry.

I'm running into a problem when I am working with checkboxes, though. I'm trying to retrieve the array of selected values, but I am unable to retrieve more than one. I believe that this is because I am not properly setting the checkbox names to an array, but I am not certain.

Here is where I am generating the checkbox tags:

$answers = explode(',',$answerKey);
for($i=0; $i < count($answers); $i++) {
    $questionTag .= "<INPUT TYPE='checkbox' name='$id' value='$answers[$i]' />$answers[$i]";
    }

Yet when I post back my results, the results of $_POST["$id"] only returns the last value in the checkbox list.

Any suggestions would be appreciated!

3
  • 1
    Instead of name='$id' and guess fot the location of the checkbox value, use name="someOption[]" with a sensible value: all someOptions will now be in an array $_POST['someOption'] Commented Apr 27, 2011 at 17:02
  • Are all the checkboxes relates to one group? Commented Apr 27, 2011 at 17:10
  • For any element that has checkboxes, all of the checkboxes will relate to that group, but there can be more than one group of checkboxes on the form. Commented Apr 27, 2011 at 17:38

1 Answer 1

2
$questionTag .= "<INPUT TYPE='checkbox' name='".$id."[]' value='$answers[$i]' />$answers[$i]";
Sign up to request clarification or add additional context in comments.

2 Comments

Be aware that will not create a group of checkboxes as this will return only one check box with unique name eg 1[]
No, that works perfectly. It does create a group of checkboxes, since I am iterating through a list of $answers[$i] values, but name='".$id."[]"' gets repeated for each iteration without the $id value changing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.