Alexandre Rocha Alexandre Rocha - 2 months ago 4
PHP Question

When I choose a option from a select, this option don't show in the other select

I'm doing a exercise in html, php that calculate the distances from the cities, the professor ask to do a select, and when you choose City A in a select, you cant choose City A in the other select. How can I do This?

HTML code:

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Distance</title>
</head>
<body>
<form method="GET" action="Distancia.php">
<select name="op1">
<option value="SP">São Paulo</option>
<option value="RJ">Rio de Janeiro</option>
</select>

<select name="op2">
<option value="SP">São Paulo</option>
<option value="RJ">Rio de Janeiro</option>
</select>
<input type="submit" value="Enviar"/>
</form>

</body>
</html>


php code:

<?php
$opcao1 = isset($_GET['op1']) ? $_GET['op1'] : false;
$opcao2 = isset($_GET['op2']) ? $_GET['op2'] : false;
echo "The distance between $opcao1 e $opcao2 is";
?>


Can somebody help-me?

Answer

I think this will solve what you want but note that you have to make only one file (Distancia.php)

<?php
$cities = array('SP' =>"São Paulo"  ,'RJ' =>"Rio de Janeiro");
$cities2 = $cities;
$city1 = $_GET['op1'];


if (isset($city1)){
    unset($cities2[trim($city1)]);
} 


if (isset($_GET['op1']) && isset($_GET['op2']) && $_GET['op2'] != '0' && $_GET['op1'] != $_GET['op2'] ) {
$cities2 = $cities;
$city1 = 0;
$opcao1 = isset($_GET['op1']) ? $_GET['op1'] : false;
$opcao2 = isset($_GET['op2']) ? $_GET['op2'] : false;
echo "The distance between $opcao1 e $opcao2 is";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Distance</title>
</head>
<body>
<form method="GET" action="Distancia.php">
    <select name="op1" onchange="this.form.submit()">
    <option value="0">choose</option>
    <?php foreach($cities as $key => $value) {?>
            <option value="<?php echo $key ?>" <?php if($key== $city1) echo "selected"?>><?php echo $value ?></option>
    <?php } ?>
    </select>

    <select name="op2">
    <option value="0">choose</option>
    <?php foreach($cities2 as $key2 => $value2) {?>
            <option value="<?php echo $key2 ?>"><?php echo $value2 ?></option>
    <?php } ?>
    </select>
    <input type="submit" value="Enviar"/>

Comments