Changing Default Select Value Depending On GET

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ChipChamp
Forum Newbie
Posts: 13
Joined: Sun May 20, 2007 8:40 pm

Changing Default Select Value Depending On GET

Post by ChipChamp »

Using PHP, is there a way that I can change the default value of a select box and a text box?

I just made a search form for a bunch of poems on one of my sites, and it works fine and all, but if you search "Dark" poems including the word "and" , it works fine, but once it loads the search the select form goes back to the first value (which is all poems), and the text area goes blank. Then, someone may forget to change those again so if they search for a new word like... "run", it will search all poetry and not just dark poetry, what they might have expected. If that made any sense...

So, is there any way to change the default value of those depending on GET variables in the url?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

You need to loop the values of your select box and check if the value matches the value in the url, and if it does output selected = selected, ie.

Code: Select all

foreach ($selectboxValues as $value => $label) 
{
   echo '<select value="'. $value .'";
   if ($value == $_GET['value']) echo 'selected = selected';
   echo '> '. $label .'</select>';
}
Of course, you'll need to verify $_GET['value'] exists before using it tho ;)
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

I think Jcart meant "<option>" instead of "<select>" :)

My code:

Code: Select all

function option_print($label, $value, $selected)
{
    echo "<option value='$value'".($selected == $value ? " selected='selected'" : "").">$label</option>\n";
}
array_walk($selectboxValues , 'option_print', $_GET['value']);
There are 10 types of people in this world, those who understand binary and those who don't
ChipChamp
Forum Newbie
Posts: 13
Joined: Sun May 20, 2007 8:40 pm

Post by ChipChamp »

Thanks! I didn't use that exact way, but it helped me make an efficient way to do it for mine. :)
Post Reply