【问题标题】:How do I set the value of Asp.Net DropDownList using jQuery?如何使用 jQuery 设置 Asp.Net DropDownList 的值?
【发布时间】:2021-10-24 21:40:55
【问题描述】:

我有一个 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>

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

这是用于将值从 Web API 设置到字段的 jQuery:

 $("#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”。如何自动填充下拉字段?

【问题讨论】:

    标签: javascript html jquery asp.net webforms


    【解决方案1】:

    您可以为此使用 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>
    

    【讨论】:

    • 但这会在下拉列表中添加一个新的列表项吗?我想从现有列表项中设置文本。
    • 这样的? $DeptDll.find('option[value=HR]').text('Human Resources 1');
    猜你喜欢
    • 2010-09-22
    • 2011-11-18
    • 2013-01-22
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2019-12-15
    相关资源
    最近更新 更多