How I can remove an Item for a select option html pressing a button with php

Viewed 19

Im tryng to create a simple application that when you click on the send button it removes the option that is selected. I only can use PHP and no JS.

    <form action="prueba.php" method="POST">
      <select name="cars" id="cars">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>
        
      <input type="submit" value="Eliminar">
<form>
1 Answers

You can do this with some sort of data storage. In this case I'm using sessions, but you could use a database.

<?php 
session_start();

if(!isset($_SESSION['removed_options'] )){
    $_SESSION['removed_options'] = [];
}
if(isset($_POST['Eliminar'])){
    $_SESSION['removed_options'][] = $_POST['cars'];
}

$options = ["volvo", "saab", "opel", "audi"];
?>

<form action="prueba.php" method="POST">
    <select name="cars" id="cars">
        <?php foreach(array_diff($options, $_SESSION['removed_options']) as $option): ?>
            <option value="<?= $option ?>"><?= ucfirst($option) ?></option>
        <?php endforeach; ?>
    </select>

    <input type="submit" value="Eliminar" name="Eliminar">
<form>

You could also possibly store the options in a hidden field on the frontend now that I think about it.

Related