【问题标题】:how to use javascript to populate value in a dropdownlist as selected from a textbox如何使用javascript填充从文本框中选择的下拉列表中的值
【发布时间】:2020-12-04 13:50:00
【问题描述】:
我有一个这样的下拉列表:
<asp:DropDownList ID="ddlsex" runat="server">
<asp:ListItem>male</asp:ListItem>
<asp:ListItem>femle</asp:ListItem>
<asp:ListItem>unknown</asp:ListItem>
</asp:DropDownList>
我还有一个文本框:
<asp:TextBox ID="txt" runat="server" ></asp:TextBox>
所以我想使用 JavaScript 来实现,当我在文本框中输入男性时,下拉列表将显示选择男性,或者输入女性,下拉列表将显示选择女性。如果它们都没有,则警告没有这样的选项。
有人可以帮忙吗?
【问题讨论】:
标签:
javascript
c#
asp.net
drop-down-menu
【解决方案1】:
<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>
【解决方案2】:
首先用你的下拉菜单定义 values 属性
<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>
在 .aspx 表单中包含 JQuery 库
<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>