简体   繁体   中英

how to use javascript to populate value in a dropdownlist as selected from a textbox

I have a dropdown list like this:

<asp:DropDownList ID="ddlsex" runat="server">
<asp:ListItem>male</asp:ListItem>
<asp:ListItem>femle</asp:ListItem>
<asp:ListItem>unknown</asp:ListItem>        
</asp:DropDownList>

and I also have a textbox:

<asp:TextBox ID="txt" runat="server" ></asp:TextBox>

so I want to use JavaScript to realize that when I type in the textbox male, the dropdown list will show male selected, or type female, the dropdown list will show female selected. if none of them, then alert no such option. can anybody help with this please.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#TextBox1").change(function () {
            alert($("#TextBox1").val());
            alert("Test");
            $("#DropDownList1").val($(this).val());
        });
    });
</script>

First define values attribute with your dropdown

<asp:DropDownList ID="ddlsex" runat="server">
<asp:ListItem Value="male">male</asp:ListItem>
<asp:ListItem Value="female">femle</asp:ListItem>
<asp:ListItem Value="unknown">unknown</asp:ListItem>        
</asp:DropDownList>

<asp:TextBox ID="txt" runat="server"></asp:TextBox>

Include the JQuery library in your.aspx form

<script src="Scripts/jquery-3.4.1.js"></script>
<script>
    $(document).ready(function () {
        var txtCtrl = $('#<%=txt.ClientID%>');

        //On focusing out the textbox I'm setting value of dropdown.
        //You can change it to anything else here
        txtCtrl.focusout(function () {
            var ddCtrl = $('#<%=ddlsex.ClientID%>');
            ddCtrl.val(txtCtrl.val());
        });
    });
</script>

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