使用 PHP 从下拉列表中清除所选项目
我使用下面的代码从下拉列表中删除选定的项目,但是当我删除一个项目时,会弹出另一个项目。例如,如果我的选项是:“枪支、汽车、金钱”,当我选择并删除枪支时,汽车和金钱仍然存在。但是,如果我选择汽车并将其删除,则会再次弹出已删除的枪支选项。这令人沮丧。
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PHP 仅在页面加载时起作用,并且您一遍又一遍地加载相同的代码。为了使以前删除的选项保持删除状态,您需要某种数据持久性(例如数据库)。否则,您可以使用 JavaScript 来操作客户端浏览器上的选择选项。 这里有一个很好的讨论
如果您必须将操作绑定到
onclick( )
并在服务器端接收事件,那么您将需要使用 AJAX 调用。onclick
调用一个单独的 PHP 脚本,该脚本删除该选项并返回某种成功消息。PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to
onclick()
and receive the event on the server side, then you will need to use an AJAX call. Theonclick
calls a separate PHP script which deletes the option and returns some kind of success message.你想看看一些 js 代码来做到这一点。看看类似的东西 http://www.mredkj.com/tutorials/tutorial_mixed2b.html
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
使用jquery
jquery 自动建议
use jquery
jquery auto suggestion