Jump to content

[SOLVED] function for multiple checkbox groups on one page


jmotes

Recommended Posts

Hello everyone,

 

I am trying to write a function that takes an array of options and presents them to the user. The catch is that I need to reuse it several times on one page to create multiple unique checkbox groups.

 

I know that one usually makes the name attribute of each input tag match the name of the array of items that is being presented to the user, like this:

<input type="checkbox" id="color1" name="colors[]" value="white" />

 

But I need to be able to set a unique name for each group of checkboxes. I've written some code to try to create a dynamically named array, but it isn't working.

 

Does anyone know what's wrong with my code, or if there is a better way of doing this?

<?php

if(isset($_POST['submit']))
{
print_r(array_keys($_POST));
}

$colors = array('red','blue','green','yellow','purple','black','white','orange','pink');

function listOptions($options, $groupName)
{
//create dynamically named variable
$$options = $groupName;

$checkBoxName = $groupName . '[]';
$count = 0;

foreach($options as $option)
{
	$id = $groupName . $count;
	echo "\t<p><input type=\"checkbox\" id=\"$id\" name=\"$checkBoxName\" value=\"$option\" /><label for=\"$id\">$option</label></p>\n";
	$count++;
}
}
?>

<h1>Favorite colors:</h1>
<form name="test_form" method="post">
<?php listOptions($colors, 'colors'); ?>
<input type="submit" name="submit" value="Submit" />
</form>

 

Many thanks!

Wow, I just figured it out! :D

 

I was creating the dynamically named array incorrectly, it should have been

$$groupName = $options;

 

Here's my working code for others that could use it:

<?php

if(isset($_POST['submit']))
{
$groupName = $_POST['group_name'];

if(isset($_POST[$groupName]))
{
	echo "<br/>\n";
	print_r($_POST[$groupName]);
}
}

$colors = array('red','blue','green','yellow','purple','black','white','orange','pink');

function listOptions($options, $groupName)
{
//create dynamically named array
$$groupName = $options;

$checkBoxName = $groupName . '[]';
$count = 0;

foreach($options as $option)
{
	$id = $groupName . $count;
	echo "\t<p><input type=\"checkbox\" id=\"$id\" name=\"$checkBoxName\" value=\"$option\" /><label for=\"$id\">$option</label></p>\n";
	$count++;
}
}
?>

<h1>Favorite colors:</h1>
<form name="test_form" method="post">
<?php listOptions($colors, 'colors'); ?>
<input type="hidden" name="group_name" value="colors" />
<input type="submit" name="submit" value="Submit" />
</form>

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.