javascript根据另一个下拉列表自动选择下拉列表

时间:2011-05-21 04:14:48

标签: c# javascript asp.net drop-down-menu

如果我选择一个项目,我在我的页面上有2个下拉列表,应该在另一个下拉列表中显示相同的选项。任何人都可以javascript为我提供Javascript而不是Jquery

3 个答案:

答案 0 :(得分:1)

您可以在下拉列表中附加onchange事件。 然后,只要您选择的索引发生更改,它就会触发并调用提供的更新方法。 例如:

HTML

<asp:DropDownList id="FirstDropdown" onChange="javascript:update();" ...>

的JavaScript

<script type="text/javascript">
function update ( ) {        
   document.getElementById('<%= SecondDropdown.ClientID %>').value =
   document.getElementById('<%= FirstDropdown.ClientID %>' ).value;        
}

答案 1 :(得分:1)

这是对你所描述内容的一个非常简单的实现:

给出html:

<select id="select1">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
</select>
<select id="select2">
  <option value="foo">foo</option>
  <option value="bar">bar</option>
</select>

和这个javascript:

document.getElementById('select1').onchange = function(e) {
  var index = this.selectedIndex;
  document.getElementById('select2').options[index].selected = true;
}

你可以实现你想要的。请注意,两个选择框中的索引应完全相同(因为选项应按相同的顺序排列)

答案 2 :(得分:0)

试试这个

<asp:DropDownList ID="ddl1" runat="server">
            <asp:ListItem Value="1"></asp:ListItem>
            <asp:ListItem Value="2"></asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem Value="4"></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
            <asp:ListItem>4</asp:ListItem>
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>



  <script type="text/javascript">
function MyApp(sender){
    var lbMatch = false;
    var loDDL2 = document.getElementById('DropDownList1');
    for(var i=0; i< loDDL2.length-1; i++){
        lbMatch = sender.value==loDDL2.options[i].value;       
        lsSelected = lbMatch ? "<=SELECTED" : "";
        if(lbMatch)
            loDDL2.selectedIndex = sender.selectedIndex;
    }
}
        </script>

在页面加载事件中添加此

  ddl1.Attributes.Add("OnChange", "MyApp(this)");
相关问题