Reputation: 101
I'm doing an exercise in HTML and PHP that calculates the distances from the cities. Professor asked to implement a select in such a way that when you choose City A in one select dropdown, you shouldn't be able to choose City A in the other select dropdown. How can I achieve 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 out with the problem?
Upvotes: 1
Views: 119
Reputation: 190
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"/>
Upvotes: 1
Reputation: 31
you can try it enter code here if($opcao1 &&($opcao1 == $opcao2)) { echo $opcao1.'has be choosed,plase choose other city'; }
Upvotes: 0