如何根据另一个下拉列表中的选择在下拉列表中选择一个选项

时间:2011-08-06 08:11:20

标签: php javascript drop-down-menu

我有两个已从数据库中填充的DropDown列表。如果您在DropDownlist1中选择一个值 - Dropdownlist2将获得与Dropdownlist1中选择的值相同的值。

但代码基于switch case,而且选项也是硬编码的!将来 - 很多选择可能会出现,它将无法运作!

所以我想要的是如果您在下拉列表1中选择一个选项 - 应该在DropDown列表2中根据“值”选择该选项而不是“索引”Like here

任何指针或帮助将不胜感激!提前致谢

 function showSelected(f) {

var selNum  = f.type1.selectedIndex;
//var selText = f.type1.options[selNum].text


switch (selNum)
{
case 1:
document.getElementById('type2').selectedIndex= 2;
break;

case 2:
document.getElementById('type2').selectedIndex = 8;
break;

case 3:
document.getElementById('type2').selectedIndex = 3;
break;

case 4:
document.getElementById('type2').selectedIndex = 1;
break;

case 5:
document.getElementById('type2').selectedIndex = 4;
break;

case 6:
document.getElementById('type2').selectedIndex = 2;
break;

case 7:
document.getElementById('type2').selectedIndex = 2;
break;

case 8:
document.getElementById('type2').selectedIndex = 7;
break;

}


}

 <select name="Type1" id="Type1" onchange="showSelected(this.form)" >
<option>Select Option</option>
    <option  value="<?php echo $record->getID();?>" > <?php echo $record->getIDName();?> </option>
 </select>       

 <select name="Type2" id="Type2" disabled>
<option>Select Option</option>
    <option  value="<?php echo $record->getID();?>" ><?php echo $record->getIDValue();?> </option>
 </select>     

2 个答案:

答案 0 :(得分:3)

function selectoption()
    {
        var list = document.getElementById('list');
        var listtwo = document.getElementById('listtwo');
        var searchtext = list.options[list.selectedIndex].text; 
        for(var i = 0; i < listtwo.options.length; ++i)
            if (listtwo.options[i].text === searchtext) listtwo.options[i].selected = true;
    }

http://jsbin.com/oyaloc/2

答案 1 :(得分:0)

当您打印出选择框中的所有选项时,您可以在数组中提供与其索引相关的选项ID:

<select id='first_combo_box' onchange='selected(this);'>
<?php
  foreach( $arrayOfOptions as $index => $option ):
?>
    <option value='<?php echo $option?>' id='first_combo_index_<?php echo $index?>'><?php echo $option ?></option>
<?php
  endforeach;
?>
</select>

<select id='second_combo_box' onchange='selected(this);'>
<?php
  foreach( $arrayOfOptions as $index => $option ):
?>
    <option value='<?php echo $option?>' id='second_combo_index_<?php echo $index?>'><?php echo $option ?></option>
<?php
  endforeach;
?>
</select>

然后在你的javascript中:

function selected(selectElt) {
  var index = selectElt.selectedIndex;
  document.getElementById('first_combo_index_' + index).selected = true;
  document.getElementById('second_combo_index_' + index).selected = true;
}

解析你要发送给函数的'select'元素非常容易,所以你只能更改OTHER select元素的选定选项,但是已经很晚了,我累了所以我会留给你:)

相关问题