使用 PHP $_POST 记住选择框中的选项?
我有一个可以发布到自身的表单,以便用户可以执行您在购物车中找到的操作。
例如增加数量,选择邮资类型。
我的问题是,每当表单重新加载时,我的表单选择名为“邮资”的元素,它就会忘记选择的内容。
我的所有其他字段都使用以下方法记住它们的值:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value toautomatic select the option in the select field that was made by the user?
我试过这个:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
还有这个
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
谢谢
I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called "postage" whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
你几乎明白了。您需要在
上设置属性
selected="selected"
(技术上您需要的确切形式取决于您的 HTML 文档类型,但这是安全的默认值) > 元素当且仅当$postage
的值等于该元素的值。所以:请注意,这违反了 DRY 原则,因为现在字符串
"foo" 出现了两次
在那里,所以它是重构的主要候选者。一个好的方法是将值/文本对保存在数组中,并使用foreach
对其进行迭代以生成标记。
You almost got it. You need to set the attribute
selected="selected"
(the exact form you need technically depends on your HTML doctype, but this is a safe default) on the<option>
element if and only if the value of$postage
equals the value of the element. So:Note that this violates the DRY principle because you now have two occurrences of the string
"foo"
in there, so it's a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it withforeach
to produce the<option>
tags.您需要遍历所有选项。
使用所有下拉选项创建一个数组,循环遍历该数组,然后与 post 中存储的内容进行比较。
例如:
You need to foreach through all the options.
Make an array with all the dropdown options, loop through that, and compare with what is stored in post.
E.G.:
不,它根本不起作用......你需要为此设置某种循环。
编辑:
我认为这可能对你有帮助......你可以问我是否还需要任何东西......
谢谢。
no its not working at all..you need to put some kind of loop for that.
EDITED:
I think this may be helpful to you..you can ask me if anything else needed...
Thanks.
selected 的值应该被选中
The value of selected should be selected
你的html语法是错误的。正确的html写法是这样的:
Your html syntax is wrong. The correct way to write the html is like this:
您还可以将其缩短:
You can also make it shorter: