繁体   English   中英

如何使用 jQuery 设置 Asp.Net DropDownList 的值?

[英]How do I set the value of Asp.Net DropDownList using jQuery?

我有一个 Asp.Net 表单:

<div id="my-fields">
   <asp:TextBox ID="Name" runat="server" />
   <asp:TextBox ID="Age" runat="server" />
   <asp:DropDownList ID="Dept" runat="server" required="true">
        <Items>
             <asp:ListItem Text="Human Resources" value="HR"/>
             <asp:ListItem Text="Information Technology" value="IT"/>
        </Items>
   </asp:DropDownList> 
</div>

在“名称”TextBox 中输入文本时,我正在调用 AJAX Web API,它获取 Age 和 DropDownList 字段的值并使用这些值自动填充这些字段。

这 jQuery 将值从 Web API 设置为字段:

 $("#my-fields input[id*='Name']").val(name);
 $("#my-fields input[id*='Age']").val(age);
 ***$("#my-fields select[id*='Dept']").val(dept);***

问题是我从 Web API 得到的“部门”的价值是,例如:“人力资源”。 ListItem 的值为“HR”。 如何自动填充下拉字段?

您可以为此使用 jQuery append

<asp:DropDownList ID="Dept" runat="server" required="true" ClientIDMode="Static">
    <Items>
        <asp:ListItem Text="Human Resources" Value="HR" />
        <asp:ListItem Text="Information Technology" Value="IT" />
    </Items>
</asp:DropDownList>

<script>
    var $DeptDll = $('#Dept');

    //if you want to empty it first
    $DeptDll.empty();

    $DeptDll.append($('<option></option>').text('New Text Value').val('NTV'));
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM