在提交后选择选择框 [英] Keep a Select Box Selected after Submit

查看:203
本文介绍了在提交后选择选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上,用户可以按类型过滤游戏。当用户从选择框中选择类型并点击提交时,页面使用GET来查看过滤器是什么。现在过滤器工作正常,问题是选择框的选择到默认的(这说全部。)

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.

只有一种方法,我可以想到这样做,但它需要添加PHP到每个选项都有。有没有更简单的方法去使用PHP或jQuery做这个?

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?

推荐答案

假设你做一个完整的表单提交选择的选项只对服务器端代码可用,一旦它回到客户端使用jQuery,你不会有这个(除非你尝试在提交表单前使用cookie,但是bleh)。

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).

我会在选项标签中使用PHP,如果选项与选定的选项匹配,则返回 selected =selected

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>

这篇关于在提交后选择选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆