Jump to content

Checkbox same name, different value problem


domdeez

Recommended Posts

I've set up a simple multi-page form. I am passing the form data from page to page using hidden fields. I do so by adding the piece of code listed below between the form tags of the receiving page.

 

<?php

  foreach($_POST as $key=>$value){

    if ($key!="submit"){

      $value=htmlentities(stripslashes(strip_tags($value)));

      echo "\t<input type=\"hidden\" name=\"$key\" value=\"$value\">\n";

    }if (is_array($value)) {

$value = implode(",",$value);

}

  }

 

 

?>

 

Here's the problem. On the first page there are checkboxes with the same name but different values.  The hidden fields that appear on page 2 only show the first value of this checkbox (when multiple boxes are selected).  I've seen solutions like this below, but haven't found a way to get them to work with the code above.  Can someone point me in the right direction?  Thanks.

 

Retrieving Multiple Checkbox Values As An Array If brackets are missing on names;

 

...

<INPUT TYPE="checkbox" NAME="s" VALUE="A" CHECKED>Checkbox 1<BR>

<INPUT TYPE="checkbox" NAME="s" VALUE="B">Checkbox 2<BR>

<INPUT TYPE="checkbox" NAME="s" VALUE="C">Checkbox 3<BR>

...

processing script

 

<?php

echo '<PRE>('.(gettype($_POST['s']).') ';

print_r($_POST['s']);

?>

will produce:

 

(string) A

 

But if you add [] after each element’s name,

 

...

<INPUT TYPE="checkbox" NAME="s[]" VALUE="A" CHECKED>Checkbox 1<BR>

<INPUT TYPE="checkbox" NAME="s[]" VALUE="B">Checkbox 2<BR>

<INPUT TYPE="checkbox" NAME="s[]" VALUE="C">Checkbox 3<BR>

...

the same PHP code will produce the output below:

 

(array)

Array (

    [0] => A

    [1] => B

    [2] => C

)

 

keep the [] in the form makes it easier to process

 

[] will return an array, and the function u posted will handle numerics or strings

 

so build a function

 

function createhidden($post,$inp='')
{
   foreach($post as $key => $val)
   {
       if(is_array($val)) createhidden($val,$key);
       else {
        $val=htmlentities(stripslashes(strip_tags($val)));
         echo '<INPUT TYPE=HIDDEN name="' . (!empty($inp)?"$inp\[\]":$key) . "\" VALUE=\"$val\">\n";
   }
}

 

notice it calls itself on arrays :)

 

so ya can call it up as

 

 

createhidden($_POST);

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.