当我从选择中选择一个选项时,该选项应隐藏在另一个选项中

时间:2016-09-20 00:22:06

标签: php html5

我正在用HTML和PHP进行练习,计算与城市的距离。教授要求以这样的方式实施选择:当您在一个选择下拉列表中选择城市A时,您不应该在另一个选择下拉列表中选择城市A.我怎样才能做到这一点?

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代码:

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

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我认为这会解决你想要的问题,但请注意你必须只制作一个文件(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"/>

答案 1 :(得分:0)

你可以尝试一下     在此处输入代码     if($ opcao1&amp;&amp;($ opcao1 == $ opcao2))     {       echo $ opcao1.'has be beosed,plase choose other city';     }