...

View Full Version : Reproducing chosen <select> option with large lists



cyphix
06-09-2007, 11:08 PM
Hey guys... if say I have a <select></select> field with many many options & the users selects an option & submits the form..... now, if there was an error on the submission I am going to reload the form with the error & load all their answers into the fields....

My question is.... is there a quicker way to make their answer in the select field the selected option (<option value="blah" selected>blah</option>) other than looping through each & every field as they are output on the page to see if that was the answer they selected?

Cheers for any ideas!

mr e
06-09-2007, 11:28 PM
Variable variables (http://www.php.net/variables.variable)

They're a bit complicated at first, but come in handy every so often



$$_POST['blah'] = 'selected="selected"';

echo '<select name="blah">';

echo '<option value="opt_1" '. $opt_1 .'>1</option>';
echo '<option value="opt_2" '. $opt_2 .'>2</option>';
echo '<option value="opt_3" '. $opt_3 .'>3</option>';

echo '</select>';

digital-ether
06-10-2007, 01:21 AM
Variable variables (http://www.php.net/variables.variable)

They're a bit complicated at first, but come in handy every so often



$$_POST['blah'] = 'selected="selected"';

echo '<select name="blah">';

echo '<option value="opt_1" '. $opt_1 .'>1</option>';
echo '<option value="opt_2" '. $opt_2 .'>2</option>';
echo '<option value="opt_3" '. $opt_3 .'>3</option>';

echo '</select>';


pretty nifty... very simple.

This would be susceptible to XSS if Register Globals is turned on however.
Would also generate E_NOTICE level errors (not really a worry if you're using it on your own server).

I can't find anything as simple as that, but here is another solution:



$bla = isset($_POST['blah']) ? $_POST['blah'] : false;

echo '<select name="blah">';

echo '<option value="opt_1" '. $bla == 'opt_1' ? 'selected="selected"' : '' .'>1</option>';
echo '<option value="opt_2" '. $bla == 'opt_2' ? 'selected="selected"' : '' .'>2</option>';
echo '<option value="opt_3" '. $bla == 'opt_3' ? 'selected="selected"' : '' .'>3</option>';

echo '</select>';

cyphix
06-10-2007, 01:38 AM
Thanks guys!! :thumbsup:

marek_mar
06-10-2007, 01:44 AM
Having PHP throw this many errors could actually be slower.
You should be looping through all the options anyway if you tore them in the database.
An alternative would be to have the selected item twice in the select box - as the first option and in the place in which it's supposed to be.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum