Populate 2nd dropdown by first dropdown value in a

2019-02-28 22:06发布

问题:

I'm having a bit of trouble using asp.net vb What I want to do is have 2 dropdown boxes

The first dropdown would have 1 2 3 for example.

the second dropdown would have a b c by default.. but

If 1 is selected I want the second dropdown to automatically select c. I don't know if JavaScript is the best answer or if anyone has done this before I would really appreciate your advice. Thank you!

回答1:

You can do it server side or in Java Script. The general concept is the same though. You have to target the second dropdown in the "change" event of the first dropdown. Meaning whenever the change event fires for the first one, you update the second one

Sudo code:

Dropdown1_Changed()
{
  //if "1" is selected in Dropdown1, update Dropdown2 to select "c"
}


回答2:

I would proboby use the SelectedIndexChanged event on the first dropdownlist. Like this:

ASPX

<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddl2" runat="server">
    <asp:ListItem Text="A" Value="A"></asp:ListItem>
    <asp:ListItem Text="B" Value="B"></asp:ListItem>
    <asp:ListItem Text="C" Value="C"></asp:ListItem>
</asp:DropDownList>

VB

Private Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl1.SelectedIndexChanged
    If ddl1.SelectedValue = "1" Then
        ddl2.SelectedValue = "C"
    End If
End Sub


回答3:

You can use Javascript Onchange event.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function NumbersDropDownList_OnChange() {
            var numbersDropDownList = document.getElementById("numbersDropDownList");
            if (numbersDropDownList.options[numbersDropDownList.selectedIndex].text=="1") {
                document.getElementById("lettersDropDownList").selectedIndex = 2;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="numbersDropDownList" onchange="NumbersDropDownList_OnChange()" runat="server">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem>2</asp:ListItem>
            <asp:ListItem>3</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="lettersDropDownList" runat="server">
            <asp:ListItem>a</asp:ListItem>
            <asp:ListItem>b</asp:ListItem>
            <asp:ListItem>c</asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>