简体   繁体   中英

Using javascript or PHP how can I use the value from a drop down list or a text box.

How can I submit the value of either a drop down list or a text box.

<select>
<option value="none" selected>None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

<input type="text" name="newCar"/>
<input type="submit" value="Done">

If the desired car is not on the list I'd like to write it in a text box and submit the form. So it should say 1) if value selected from drop down list and text box empty use select value 2) if the default value "none" selected and some value in "newCar" then submit text box value 3) if value selected from drop down list and text box contains a value error message should be displayed

Name your select

   <select name="cars">
    <option value="none" selected>None</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
    </select>

Then get the value of your select by using $_POST['cars'].

Add name="car" for the select:

<select name="car">
<option value="none" selected>None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

<input type="text" name="newCar"/>
<input type="submit" value="Done">

In the PHP:

$request = $_REQUEST;

$car = '';
if(isset($request['car'])){
    $car = $request['car'];
}
$newCar = '';
if(isset($request['newCar'])){
    $newCar = $request['newCar'];
}
// case 1)
if($car != 'none' AND $newCar == ''){
      echo $car." was selected selected";
}

// case 2)
if($car == 'none' AND $newCar != ''){
      echo $newCar ." was selected selected";
}

// case 3)
if($car != 'none' AND $newCar != ''){
      echo "ERROR! plz select only one option.";
}

I use your example, you could optimize the PHP.

You can get both the value of the select and the text box with PHP if you use a name with [] at the end, ie, setting name to "newCar[]" on both your select and your input:

<select name="newCar[]">
    <option value="" selected>None</option>
    ...
</select>

<input type="text" name="newCar[]" />
<input type="submit" value="Done" />

Then your values will be in the array $_REQUEST['newCar']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM