Jump to content

Generating a select box with a function


Eckels

Recommended Posts

I've written the following really simple function

 

function dodropbox($fieldname, $num, $sel)
{
echo "<select id='$fieldname' name='$fieldname'>";
$counter = 0;
while ($counter < $num)
{
if ($counter == $sel)
	{
	echo "<option value='$counter' selected>$counter</option>";
	$counter++;
	}
else
	{
	echo "<option value='$counter'>$counter</option>";
	$counter++;
	}
}
echo "</select><br />";
}

 

Then I call it with

 

dodropbox('field_name','100','$retrieved_value');

 

fieldname is the form field name, 100 is the total number of options, and $retrieved_value is a value retrieved from the database to fill the form in, as this is an edit form, for previously entered values.

 

The code works, the box is generated. The problem lies with setting the "selected" option. I know $retrieved_value is there, as I can print, and echo it.

 

This seems to be the problem - so why doesn't it work?

if ($counter == $sel)
	{
	echo "<option value='$counter' selected>$counter</option>";
	$counter++;
	}

 

I'd appreciate any help you can give. This is frustrating me. I'm sure it's a simple thing, but I've just been staring at it too long. Do I need to do something fancy to pass a variable to a function?

 

Link to comment
https://forums.phpfreaks.com/topic/100779-generating-a-select-box-with-a-function/
Share on other sites

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.