DropDown必须在POST后保留文本 [英] DropDown must retain the text after POST
问题描述
我想在表单从POST返回时保留DropDown文本。如何保持状态?
您必须设置选中
属性选项
元素。
请参阅 http://reference.sitepoint.com/html/option/selected
< ;形式>
< label for =favoritefood>最喜欢的食物< / label>
< option value =che>奶酪< / option>
< option value =eggselected =selected> Egg< / option>
< option value =cab>卷心菜< / option>
< / select>
< / form>
$ _ POST
数组将包含选项元素的数字索引或值
(如果指定了此属性)。在上面的例子中, $ _ POST ['favoritefood']
包含'egg'。你可以建立一个助手来为你建立选项元素,例如
<?php
class HtmlHelper
{
public static function option($ value,$ label,$ selected)
{
$ selected =($ value === $ selected)? 'selected =selected':'';
return sprintf('< option value =%s%s>%s< / option>%s',
$ value,$ selected,$ label,PHP_EOL);
//用于获得上述选择框选项
echo HtmlHelper :: option('che','Cheese',$ _POST ['favoritefood']),
HtmlHelper :: option('egg','Egg',$ _POST ['favoritefood']),
HtmlHelper :: option('cab','Cabbage',$ _POST ['favoritefood']] );
当然,使用Selectbox助手会更聪明,您可以将选项和POST数组,而不是分别为每个选项调用它。如果您不是通过PHP动态构建您的Select选项,您可以通过在您的页面中添加一个小的JavaScript来选择该选项。
您从$ _POST数组传递给favoritefood设置的值,并让脚本选择该选项。 请参阅此问题的答案以了解可能的代码。I want the DropDown text to be retained when the Form returns from POST. How to maintain the state?
You have to set the selected
attribute on the option
element.
See http://reference.sitepoint.com/html/option/selected
<form>
<label for="favoritefood">Favorite food</label>
<select name="favoritefood" id="favoritefood">
<option value="che">Cheese</option>
<option value="egg" selected="selected">Egg</option>
<option value="cab">Cabbage</option>
</select>
</form>
The $_POST
array will either contain the numeric index of the option element or the value
if this attribute is specified. In the example above, $_POST['favoritefood']
contains 'egg'. You could build a helper that builds the option elements for you, e.g.
<?php
class HtmlHelper
{
public static function option($value, $label, $selected)
{
$selected = ($value === $selected) ? ' selected="selected"' : '';
return sprintf('<option value="%s"%s>%s</option>%s',
$value, $selected, $label, PHP_EOL);
}
}
// Usage to get the above Selectbox options
echo HtmlHelper::option('che', 'Cheese', $_POST['favoritefood']),
HtmlHelper::option('egg', 'Egg', $_POST['favoritefood']),
HtmlHelper::option('cab', 'Cabbage', $_POST['favoritefood']);
Of course, it would be smarter to have a Selectbox helper instead which you can pass the options and the POST array in one go, instead of calling it for each option separately. I leave it up to you to build this.
If you are not building your Select options dynamically with PHP, you can select the option by adding a small javascript to your page that you pass the value set for favoritefood from the $_POST array and have the script select the option. See the answers to this question for possible code.
这篇关于DropDown必须在POST后保留文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!