如何创建一个下拉菜单,将菜单中的数据放入文本字​​段中

时间:2011-09-29 09:43:28

标签: php javascript html

我想将此功能添加到我的表单中。当选择下拉菜单中的选项时,我希望它输入上面的文本字段以及相应的信息。

objBMW = {
     "Sedan":"5-series",
     "Convertible":"6-series",
     "Truck":"X5",
     "Coupe":"3-series",
     "Hatchback":"5-series GT"
  };

<form name="form1" action="formhandler">

<input type="text" name="typecar">

<select name="BMWCars"> 
<option value="Sedan">Sedan</option> // when this option is chosen put string "5-series" in textfield above
<option value="Convertible">Convertible</option> // when this option is chosen put string "6-series" in textfield above
<option value="Truck">Truck</option> // when this option is chosen put string "X5" in textfield above
<option value="Coupe">Coupe</option> // when this option is chosen put string "3-series" in textfield above
<option value="Hatchback">Hatchback</option> // when this option is chosen put string "5-series GT" in textfield above
</select>

2 个答案:

答案 0 :(得分:1)

使用Javascript:

document.forms.form1.BMWCars.onchange = function(){
    document.forms.form1.typecar.value = objBMW[this.value];
}

http://jsfiddle.net/xZsc7/

答案 1 :(得分:1)

我会这样做:

<input type="text" name="typecar" id="typecar" />

<?php
$objBMW = array('Sedan' => '5-series', 'Convertible' => '6-series');
?>
<select name="BMWCars" id="BMWCars">
<?php
    foreach($objBMW as $key => $value)
    {
        echo '<option value="'.$value.'">'.$key.'</option>';
    }
?>
</select>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
      $('#BMWCars').change(function() {
              $('#typecar').val($("#BMWCars option:selected").val());
            }).trigger('change');
    });
</script>