Clearing a selected item from a dropdown using PHP

2019-09-05 08:53发布

问题:

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>

回答1:

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. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.



回答2:

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



回答3:

use jquery jquery auto suggestion