1

我目前有一个下拉框,而不是选择一个选项时,它将回声 -

"Your Favourite Car Is (option)

我现在需要做的是更改它,使其成为一个文本框,但用户只能输入数组中的一个选项,如果选择了另一个选项,它会说它you cannot have this as one of the choices也可以输入多个这样理论上它可以回声-

"Your Favourite Car is Mazda, Nissan, Renault!"

这是我现在正在使用的投递箱的代码。

<form method="post">
<div id="dropdown">
<?php
if(isset($_POST['cars']))
{
   $mycar=$_POST['cars'];
}
else
{
   $mycar="";
} 
$array1 = array('Volkswagen' , 'Renault' , 'Land Rover');
echo' <select name="cars" onchange="this.form.submit()">';
foreach($array1 as $cars)
{ ?>
   <option value="<?php echo $cars; ?>" <?php if($mycar==$cars) echo  "
   "selected='selected'"; ?> ><?php echo $cars; ?></option>
   <?php
}
echo'</select>
</div></form>';
?>

<div id="result">  
<?php
echo "Your favourite car is $mycar"; 
?>
</div>

编辑:我已经尝试过这个,我目前一直在回声“这辆车不在选择范围内”,没有别的,我在文本框中输入的任何内容似乎都没有影响

这是我的代码

<?php
$cars = array("Volkswagen","Renault","Land Rover");
?>
<form action="array.php" method="post">

   <center> <input type="text" name="cars" id="cars" />
  <input type="submit"  /> </center>
<?php
if (in_array($_POST, $cars)) {
    echo "Your Favourite Car is $_POST";
    }

else {
    echo "This car is not among the selection";
     }
?> 
</form>
4

2 回答 2

0

您可以通过在之前检查用户输入来轻松控制用户输入:

<form method="post">
<div id="dropdown">

<?php

// Car types
$carTypes = array('Volkswagen' , 'Renault' , 'Land Rover');
$wrongCarChoosen = false ;

if(isset($_POST['cars'])) {
    $mycar = $_POST['cars'];

    if (!in_array($mycar, $carTypes)) {
        $wrongCarChoosen = true ;
    }
}
else {
    $mycar = "";
} 

echo' <select name="cars" onchange="this.form.submit()">';
foreach($carTypes as $carName){ ?>
<option value="<?php echo $cars; ?>" 
<?php 
if($mycar == $carName) echo  "
"selected='selected'"; ?> >
<?php echo $carName; 
?></option>
<?php
}
echo'</select>
</div></form>';
?>

<div id="result">  
<?php
      if ($wrongCarChoosen) {
          echo "Your choice ".$mycar." is not contained in ".implode($carTypes, ',') ;
      }
      else {
        echo "Your favourite car is $mycar";
      }
?>
</div>
于 2013-08-23T08:26:11.387 回答
0

您必须编辑表单以接受多个值。您可以在回显文本之前检查用户值。

<form method="post">
<div id="dropdown">
<?php
$array1 = array('Volkswagen' , 'Renault' , 'Land Rover');
$error = false;
if(isset($_POST['cars']))
{
  $mycar=$_POST['cars'];
  foreach ($mycar as $car) 
  {
    if (!in_array($car, $array1))
    {
      $error = $car;
    }
  }
}
else
{
$mycar=Array();
}
echo' <select name="cars[]" multiple="multiple">';
foreach($array1 as $cars){ ?>
<option value="<?php echo $cars; ?>" <?php if(in_array($cars, $mycar)) echo  "\"selected='selected'"; ?> ><?php echo $cars; ?></option>
<?php
}
echo'</select>
<input type="submit" name="submit" value="submit" />
</div></form>';
?>

<div id="result">  
<?php
if ($error===false) echo "Your favourite car is ".implode(', ', $mycar);
else echo $error . ' is not contained by ' . implode(', ', $array1);
?>
</div>
于 2013-08-23T08:40:31.210 回答