简体   繁体   English

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

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

I have an asp.net dropdown for which I added select2 and a clear button in my page. 我在asp.net下拉列表中为其添加了select2和一个清除按钮。 When I click on clear button I would like to be able to set to the option at zero index. 当我单击清除按钮时,我希望能够将其设置为零索引。 Below is the code: 下面是代码:

If I remove the select2 part, I'm able to clear the dropdown with " ddlPatient.selectedIndex = 0; " 如果删除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"/>

Then in script try... 然后在脚本中尝试...

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

or 要么

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

Use 采用

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

instead of 代替

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

You are using ddlPatients.ClientID in one place, but hard code the id somehwere else. 您在一个地方使用ddlPatients.ClientID ,但硬编码另一个。

If you change the value of the underlying <select> element, you need to trigger its change event to cause the Select2 control to update itself to match. 如果更改基础<select>元素的值,则需要触发其change事件以使Select2控件自身进行更新以匹配。

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

ddlPatient.selectedIndex = 0;

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

Or: 要么:

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

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

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