views:

734

answers:

3

On my website, user's are allowed to filter games by Genre. When a user chooses a genre from the select box and hits submit, the page uses GET to see what the filter was. Now the filter works fine, the problem is that the select box's selection goes to the default one (Which says "All".)

I want it so that after a user submits their filter request, the select box will keep that selection after the page reloads.

There's only one way I could think of to do this but it would require adding in PHP into every option there is. Are there any simpler ways to go about doing this with PHP or jQuery?

+5  A: 

You don't want to do this with jQuery. There it is not for.

Just have the options in an array in PHP and loop over it. If the looped value matches the currently selected option, then just add the selected attribute.

E.g.

foreach ($options as $value => $label) {
    echo '<option value="' . $value . '" ' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}
BalusC
+1  A: 

Assuming you're doing a full form submit the selected option is only going to be available to the server-side code, once it gets back to the client to use jQuery you won't have that (unless you try to use cookies before the form submit, but bleh).

I'd use PHP in the option tag and echo selected="selected" if the option matches up with the selected option.

If you want to avoid a lot of duplicated code why not do something like this:

<select name="test">
<?php
$options = array(1 => 'Option 1', 2 => 'Option 2', 3 => 'Option 3');
foreach ($options as $key => $value) { 
   echo '<option value="' . $key . '"' . ($key == $_GET["test"] ? ' selected="selected"' : '') . '>' . $value . '</option>';
} ?>
</select>
Parrots
You forgot the space between `value="xxx"` and `selected="selected"`.
BalusC
Thanks, all of the filters are now being echoed like that and it solved my problem.
NessDan
Be aware that his solution is not XSS safe.
BalusC
Indeed, please scrub out the $_GET access when you write up your code, it was purely there for example's simplicity sake.
Parrots
I'm not seeing the opportunity for XSS here. At no point is user input being written to the page, inserted in a DB, or anything of the sort. If I'm missing something, please let me know, but I just don't see it.
Ryan Kinal
A: 

you can do it without a loop just change the 6 to whatever value you want when you render the page

$("#$optionId[value=6]").attr('selected','selected');
bertsisterwanda