【问题标题】:how to set selectedindex of select2 dropdown in javascript如何在javascript中设置select2下拉列表的selectedindex
【发布时间】:2017-02-02 08:15:39
【问题描述】:

我有一个 asp.net 下拉菜单,为此我在我的页面中添加了 select2 和一个清除按钮。当我单击清除按钮时,我希望能够将选项设置为零索引。下面是代码:

如果我删除 select2 部分,我可以使用“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;" />

【问题讨论】:

  • $('#ddlPatients').select2().select2('val', '0');
  • 感谢您的回复,但没有成功
  • 你有没有找到这个问题的答案?我在同样的问题上花了一天时间。显然,不可能从 JavaScript 或 JQuery 设置 Select2 的索引(他们网站上的任何地方都没有关于这么简单的文档) - 也就是说,通过序数设置 selectedIndex。

标签: javascript asp.net jquery-select2 select2


【解决方案1】:
 <asp:DropDownList ID="ddlPatients" runat="server" ClientID="”Echo”" ClientIDMode="Static"/>

然后在脚本中尝试...

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

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

【讨论】:

    【解决方案2】:

    使用

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

    而不是

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

    您在一个地方使用ddlPatients.ClientID,但在其他地方硬编码了 id。

    【讨论】:

      【解决方案3】:

      如果更改底层&lt;select&gt; 元素的值,则需要触发其change 事件以使Select2 控件更新自身以匹配。

      document.getElementById("<%=ddlPatients.ClientID %>");
      
      ddlPatient.selectedIndex = 0;
      
      $(ddlPatient).change(); // Trigger the change event.
      

      或者:

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

      【讨论】:

        猜你喜欢
        • 2016-09-16
        • 1970-01-01
        • 1970-01-01
        • 2011-03-30
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        相关资源
        最近更新 更多