簡體   English   中英

如何在javascript中設置select2下拉列表的selectedindex

[英]how to set selectedindex of select2 dropdown in javascript

我在asp.net下拉列表中為其添加了select2和一個清除按鈕。 當我單擊清除按鈕時,我希望能夠將其設置為零索引。 下面是代碼:

如果刪除select2部分,則可以使用“ ddlPatient.selectedIndex = 0; ”清除下拉列表ddlPatient.selectedIndex = 0;

$(document).ready(function() { debugger;   $("[id$=ddlPatients]").select2(); });

function btnClear_Click() {
    debugger;
    var ddlPatient = document.getElementById("<%=ddlPatients.ClientID %>");

    ddlPatient.selectedIndex = 0;
}

<asp:DropDownList ID="ddlPatients" runat="server"></asp:DropDownList>
<asp:Button ID="btnClear" runat="server" CssClass="btn btn-info" Text="Clear" OnClientClick="btnClear_Click();return false;" />
 <asp:DropDownList ID="ddlPatients" runat="server" ClientID="”Echo”" ClientIDMode="Static"/>

然后在腳本中嘗試...

 var $ddlPatients = $("select[name$=ddlPatients]");
 $('#ddlPatients').select2('val', '0');

要么

$('#ddlPatients')。select2()。select2('val','0');

采用

$(document).ready(function () { debugger; $("[id$=<%=ddlPatients.ClientID %>]").select2(); });

代替

$(document).ready(function () { debugger; $("[id$=ddlPatients]").select2(); });

您在一個地方使用ddlPatients.ClientID ,但硬編碼另一個。

如果更改基礎<select>元素的值,則需要觸發其change事件以使Select2控件自身進行更新以匹配。

document.getElementById("<%=ddlPatients.ClientID %>");

ddlPatient.selectedIndex = 0;

$(ddlPatient).change(); // Trigger the change event.

要么:

$("<%=ddlPatients.ClientID %>").prop('selectedIndex', 0).change();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM