Tuesday, January 25, 2011

Posting an unchecked checkbox value in php

Hi all!
I have recently discovered a way to return (post) values from unchecked check boxes (check box group) in from a form.
It may not be the most elegant method but it works.
The concept is create 3 arrays:
  1. for the selected values
  2. store all checkbox values as a hidden type from the second array. Then we unset or remove the selected values (checked)through a for loop
  3. Store the remaining values into a new array via reshuffle.
The below diagram shows a screen shot of the results.
I have provided the code and download links below.
It is more or less self-explanatory.




[php]

  if ($_SERVER['REQUEST_METHOD'] == 'POST'){

$boxes_checked = $_POST['check_box_'];

if(empty($boxes_checked))
{ }
else
{
$N = count($boxes_checked);
echo("You selected $N checkboxes ");
echo "

";
for($i=0; $i < $N; $i++)
{

echo($boxes_checked[$i] . " ");
}
}


$check_box_hidden = $_POST['check_box_uncheck'];
$all_checkbox_values = $_POST['check_box_uncheck'];
if(empty($check_box_hidden))
{ }
else
{
$P = count($check_box_hidden);
echo "

";
for($i=0; $i < $N; $i++) // step through the checked values { echo "

";
for($j=0; $j < $P; $j++) //pay attention to $j; stepping through all checkboxes { if ($boxes_checked[$i] == $check_box_hidden[$j] ){ unset($all_checkbox_values[$j]); } } } $unchecked_values_reshuffle= array_values($all_checkbox_values);//reshuffle }// else if(empty($check_box_hidden)) if(empty($unchecked_values_reshuffle)) { } else { $Q = count($unchecked_values_reshuffle); echo("You have unselected $Q checkboxes "); echo "

";
for($k=0; $k < $Q; $k++) { echo($unchecked_values_reshuffle[$k]. " "); } } } // if ($_SERVER['REQUEST_METHOD'] == 'POST')


[php]
download php code to return checked and uncheck values

[html]






















[html]


1

2

3

4

5


[submit button here]
Download form code here

No comments:

Post a Comment