vb.net 使用 JQuery-UI 自动完成时触发 DropDownList SelectedIndexChanged 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16799781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:46:37  来源:igfitidea点击:

Fire DropDownList SelectedIndexChanged event when using JQuery-UI Autocomplete

asp.netvb.netjquery-uiautocomplete

提问by KyleMit

I'd like to post back to the server when my combobox changes value (ideally with an AJAX call in an update panel - but one thing at a time). I'm using the I'm using the jQuery UIAutoComplete Comboboxand, unfortunately, it's interferring with the change event as I'm not changing the drop down list directly.

我想在我的组合框更改值时回发到服务器(最好在更新面板中使用 AJAX 调用 - 但一次做一件事)。我正在使用 I'm using the jQuery UIAutoComplete Combobox,不幸的是,它干扰了更改事件,因为我没有直接更改下拉列表。

I'm using the implementation detailed here.

我正在使用此处详述的实现。

Here are some choice snippets

以下是一些选择片段

HTML Body Code

HTML 正文代码

<span class="ui-widget">
    <asp:DropDownList ID="cboLang" runat="server" AutoPostBack="True">
        <asp:ListItem Value="ActionScript">ActionScript</asp:ListItem>
        <asp:ListItem Value="AppleScript">AppleScript</asp:ListItem>
        <asp:ListItem Value="Asp">Asp</asp:ListItem>
    </asp:DropDownList>
</span>

Autocomplete Javascript

自动完成 JavaScript

This is the autocomplete js that exexutes whenever a selection has been made. It will always run the function _removeIfInvalid

这是自动完成 js,每当进行选择时就会执行。它将始终运行该功能_removeIfInvalid

this._on(this.input, {
    autocompleteselect: function (event, ui) {
        ui.item.option.selected = true;
        this._trigger("select", event, {
            item: ui.item.option
        });
    },

    autocompletechange: "_removeIfInvalid"
});

Server Side Code

服务器端代码

Protected Sub cboLang_SelectedIndexChanged(sender As Object, e As EventArgs) _
        Handles cboLang.SelectedIndexChanged
    'DO OTHER STUFF HERE
    Dim alert = String.Format("alert('{0}');", "Hi")
    ScriptManager.RegisterStartupScript(Me, Me.GetType, "DropDownChange", alert, True)
End Sub

Generated Code

生成的代码

When an ASP.NET renders the page with the attached event, it produces the following code

当 ASP.NET 呈现带有附加事件的页面时,它会生成以下代码

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl00'];
if (!theForm) {
    theForm = document.ctl00;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
    theForm.submit();
    }
}
//]]>
</script>

<select id="cboLang" onchange="javascript:setTimeout('__doPostBack(\'cboLang\',\'\')', 0)"
    name="cboLang" style="display: none;">

Question

Where can I go about making changes to ensure that with each update to the autcomplete input, I can trigger a server event?

我在哪里可以进行更改以确保每次更新自动完成输入时,我都可以触发服务器事件?

采纳答案by KyleMit

There are a couple things that are helpful for answering this question. One is to take a look at JQuery-UI's own documentationon this function:

有几件事有助于回答这个问题。一个是看一下JQuery-UI自己关于这个函数的文档

// Initialize the autocomplete with the select callback specified:
$( ".selector" ).autocomplete({  select: function( event, ui ) {}}); 
// Bind an event listener to the autocompleteselect event:
$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} ); 

Essentially, what needs to happen, is something needs to signal a callback when the item has been selected (either from the menu or by typing and getting an exact match).

从本质上讲,需要发生的是,当项目被选择(从菜单中或通过键入并获得完全匹配)时,需要发出回调信号。

We can do this by modifying the default functionality demonstrated on the autocompletepage:

我们可以通过修改自动完成页面上展示的默认功能来做到这一点:

this._on( this.input, {
  autocompleteselect: function( event, ui ) {
    ui.item.option.selected = true;
    this._trigger( "select", event, {
      item: ui.item.option
    });
  },
  autocompletechange: "_removeIfInvalid"
});

This code attaches listeneres on the selectand changeevents and runs the inline defined function and the _removeIfInvalid function whenever those events fire (respectively)

此代码在selectchange事件上附加侦听器,并在这些事件触发时运行内联定义的函数和 _removeIfInvalid 函数(分别)

By implementing the following changes we can do a postback when a valid selection has been made:

通过实施以下更改,我们可以在做出有效选择时进行回发:

//attach listeners
this._on(this.input, {
  autocompleteselect: "_selectFromMenu",
  autocompletechange: "_removeIfInvalid"
});

Will get called anytime an item is selected from the menu:

任何时候从菜单中选择一个项目都会被调用:

_selectFromMenu: function (event, ui) {
  ui.item.option.selected = true;
  this._trigger("select", event, {
      item: ui.item.option
    });
  __doPostBack('', '');
},

Will get called any time the text changes:

文本更改时将被调用:

_removeIfInvalid: function (event, ui) {

  // Selected an item, automatically valid, post back
  if (ui.item) {
    __doPostBack('', '');
    return;
  }

  // Search for a match (case-insensitive)
  var value = this.input.val(),
    valueLowerCase = value.toLowerCase(),
    valid = false;
  this.element.children("option").each(function () {
      if ($(this).text().toLowerCase() === valueLowerCase) {
        this.selected = valid = true;
        return false;
      }
    });

  // Found a match, post back
  if (valid) {
    __doPostBack('', '');
    return;
  }

  // Remove invalid value...

Here's a jsfiddlewith the complete code changes, although __doPostBackis commented out because it is not being handled by anything

这是一个带有完整代码更改的jsfiddle,虽然__doPostBack被注释掉了,因为它没有被任何东西处理

A couple further note:

进一步说明:

  • I'm calling __doPostBack, but I'm relying on that method being available because of asp.net event handling generated code.
  • In order to initialize the combo box, you have to call $("#combobox").combobox();. Make sure that whatever is preforming that operation is still getting called on the return from the post back, otherwise the functionality will not come back. This is one thing to work past if you're using the code asynchronously in an update panel.
  • 我正在调用 __doPostBack,但由于 asp.net 事件处理生成的代码,我依赖该方法可用。
  • 为了初始化组合框,您必须调用$("#combobox").combobox();. 确保执行该操作的任何内容仍然在从回发返回时被调用,否则该功能将不会返回。如果您在更新面板中异步使用代码,这是一件需要解决的事情。

回答by VISHMAY

Instead of __doPostBack(this.element.attr('name'), ''); write

而不是 __doPostBack(this.element.attr('name'), ''); 写

  if (this.element.attr('onchange') != undefined &&        this.element.attr('onchange').indexOf("__doPostBack") >= 0)
                        __doPostBack(this.element.attr('name'), '');