我目前有一个下拉框,当选择其中一个选项时,它将回显 -
"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>
答案 0 :(得分: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>
答案 1 :(得分: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>