Page 1 of 1

Changing Default Select Value Depending On GET

Posted: Sat Nov 03, 2007 9:22 pm
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?

Posted: Sat Nov 03, 2007 9:30 pm
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 ;)

Posted: Sat Nov 03, 2007 10:05 pm
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']);

Posted: Sat Nov 03, 2007 10:06 pm
by ChipChamp
Thanks! I didn't use that exact way, but it helped me make an efficient way to do it for mine. :)