Jump to content

smarter way of doing this dropdown list?


katie77

Recommended Posts

Ok,

 

I've got a dropdown list that is acting as a filter on a table, so the user can select a value and the page is reloaded only showing the matching values from the database.

 

Now when the page reloads the dropdown was set to 'all' as it was first in the list, even if I'd selected a different value, this was confusing for users, so I added an initial <option> field which pulled the correct value from $_GET (code below) - however this is a little odd as it means the value appears twice!

 

Does anyone have a genius solution to this?  I've seen a <select selected="yes"> sort of thing around, but I don't know how I can tell the php to add this value dynamically?  ???

 

<select size='1' name='occupation'>
	<option>".$_GET['occupation']."</option>
	<option value='All'>All</option>
	<option value='Student'>Students</a></option>
	<option value='Professional'>Professional</option>
	<option value='Hobbyist'>Hobbyists</option>
 </select>

 

Link to comment
https://forums.phpfreaks.com/topic/79316-smarter-way-of-doing-this-dropdown-list/
Share on other sites

I've seen a <select selected="yes"> sort of thing around, but I don't know how I can tell the php to add this value dynamically?  ???

 

Here is one way you could implement the suggestions above. It's only for demonstration purposes, I would put the array near the top of the actual document.

 

<select size='1' name='occupation'>

<?php

$occupation_list = array('All','Acrobat','Clown','Juggler','Sword Swallower','Wrestler');

$occupation = $_GET['occupation'];

foreach ($occupation_list as $occ)
{
echo "<option value=\"$occ\"";

if ($occ == $occupation) { echo ' selected="selected"'; }

echo ">$occ</option>";
}

?>

</select>

This is a simple way that doesn't allow for different labels and values... but this'll get you on your way...

function helpers_form_select_s($name, $values, $selected)
{ 
$sret = "<select name='".$name."'>";
foreach($values as $v)
{
	if (strcmp($v, $selected) == 0)
	{
		$sret .= "<option selected>".$v;
	}
	else
	{
		$sret .= "<option>".$v;
	}
}
$sret .= "</select>";
return $sret;
}

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.