带有代码隐藏值 "Source:"的 jQuery 组合框

标签 jquery asp.net jquery-ui combobox

为了让它在我的页面上运行,我已经花了 12 个多小时,筋疲力尽。下面我将包含我的代码隐藏(列表源和 getter)、我的 jQuery(在“ready”函数中包装的 header 中)以及包装在 div 中的 asp.net dropdownlist 控件、按钮和输入对象。 这是combobox我正在努力实现。我发现的任何东西都没有帮助。看来这是一个将行动和值(value)观联系在一起的问题。 即,该按钮不会切换下拉列表以展开

为了更容易,我在代码框中全部大写注释,以明确指出我需要帮助的地方。只剩下两件事需要解决。谢谢 friend :-)>

现在进入代码隐藏---(不是主要问题)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    combobox.DataSource = car_list
    combobox.DataBind()
End Sub

Protected car_list As New ArrayList({
                                         "Audi",
                                         "Lexus",
                                         "BMW",
                                         "Ford",
                                         "Chevrolet",
                                         "Jeep",
                                         "Jaguar",
                                         "Toyota",
                                         "Nissan",
                                         "Honda",
                                         "Subaru",
                                         "Hyundai",
                                         "Tesla",
                                         "Mercedez",
                                         "Ferrari"
                                         })

//'This function returns the above list as either a String list, or wrapped in a tag
Function getList(ByVal listName As ArrayList, Optional ByVal tagWrapper As String = "", Optional ByVal tagId As String = "") As String
    Dim items As String = "No items in list."
    If Not tagWrapper = "" Then  //'Return as HTML Tagged Objects, a.k.a. Elements or DOM Objects or Nodes
        For Each item In listName
            If Not tagId = "" Then
                items = "<" + tagWrapper + " id=""" + tagId + """" + ">" //'Used if "id" parameter passed in
                items += item.ToString
                items += "</" + tagWrapper + ">" & vbCrLf
            Else
                items = "<" + tagWrapper + ">"
                items += item.ToString
                items += "</" + tagWrapper + ">" & vbCrLf
            End If
        Next
    Else //'Return as String Array, e.g. ["item1", "item2", "item3"]
        For Each item In listName
            Dim isFirstItem As Boolean = True
            If isFirstItem Then //'Treat the first item differently
                isFirstItem = Not isFirstItem
                items = item.ToString
            Else
                items += ", " + item.ToString
            End If
        Next
    End If

    Return items
End Function

jQuery(再次在标题中)-(这里是龙!)

$(document).ready(function () {
    $("#autocomplete").autocomplete({
        delay: 0,
        minLength: 0,
        autoFocus: true,
        //This "source:" function is pulled from the jQuery Combobox link above.
        source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response($("#combobox").children("option").map(function () {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text)))
                    return {
                        label: text.replace(
            new RegExp(
                "(?![^&;]+;)(?!<[^<>]*)(" +
                $.ui.autocomplete.escapeRegex(request.term) +
                ")(?![^<>]*>)(?![^&;]+;)", "gi"
//SOMETHING WRONG WITH THE REGEX REPLACE... THE "strong" TAGS ARE COMING THROUGH IN THE DROPDOWN :p
            ), "<strong>$1</strong>"),
                        value: text,
                        option: this
                    };
            }));
        } //END "source:"
        }); //END ".autocomplete"

    $("#combobox").combobox();
//THIS IS WHERE IT'S AT!!
//THE DROPDOWNLIST CONTROL SHOULD BE HIDDEN, BUT THIS BUTTON SHOULD TOGGLE ITS CONTENTS INTO VIEW
//Here is the code used in the "combobox" demo provided on the jQuery UI site, but for some reason
//  it doesn't work with mine. The key difference to note is that they created all their DOM
//  elements and attached the listeners etc. using the "(function ($) { });" form.
    $("#toggle").click(function () {
        // close if already visible
        if (input.autocomplete("widget").is(":visible")) {
            input.autocomplete("close");
            return;
        }

        // work around a bug (likely same cause as #5265)
        $(this).blur();

        // pass empty string as value to search for, displaying all results
        input.autocomplete("search", "");
        input.focus();
    });
});

最后是标记(使用 id 作为句柄)

<form action="#" method="post">
    <h2>Choose your favorite car</h2>
    <hr />
    <div class="ui-widget"> <!-- Autocomplete Combobox -->
        <asp:DropDownList ID="combobox" runat="server" ClientIDMode="Static"></asp:DropDownList><br />
        <input id="autocomplete" class="ui-autocomplete-input ui-widget ui-widget-content ui-corner-left" style="margin-right:0;" />
        <button id="toggle" type="button" tabindex="-1" title="Show All Items" class="ui-button ui-widget ui-state-default ui-button-icon-only ui-corner-right ui-button-icon" role="button" aria-disabled="false" style="margin:0 0 0 -7px;">
            <span class="ui-button-icon-primary ui-icon ui-icon-triangle-1-s"></span><span class="ui-button-text" style="padding:0;">&nbsp;</span>
        </button>
    </div>
</form>

为了更清楚一点,组合框 ui-widget div 内的按钮和输入对象都应链接到 asp.net 控件。我对控制并不严格,但两种方法我都尝试过,但都没有成功。

编辑:哇哦!!我进行了以下更改并使数据源正常工作。现在我只需修复按钮以使其切换下拉列表的 View 。

//In the jQuery "source" section I replaced
response(select.children("option").map(function ()
//with
response($("#combobox").children("option").map(function ()

最佳答案

这是我几个月前解决的解决方案,现在有时间发布它。将来我希望修改这个 Javascript 以支持选项组:)

基本上,我将所有 JS 放入一个单独的文件中,并为我想要创建的每个组合框调用传入 DropDownListTextBox 的自定义函数。使用 SqlDataSourceDataSourceID 提供给 DropDownList,以从我的数据库填充它。 ASP.NET 将其呈现为一个 元素中每个相应的

  • 的隐藏
      。这些项目通过 response($(ddl).children("option").map(function () {...) 行找到。请注意,将 'children' 替换为 'find' 将返回 标记内的选项。

      以下是我的标记,它调用 JS 函数,然后是 JS 函数本身:

      <!-- Head section -->
      <script type="text/javascript">
          function pageLoad() {
              cbsetup("#TextBoxID", "#DropDownBoxID");
          });
      </script>
      
      <!-- Body section - SAMPLE COMBOBOX -->
      <span>
          <asp:DropDownList ID="DropDownBoxID" runat="server" DataSourceID="SDS"
              DataTextField="Name" DataValueField="ID"></asp:DropDownList>
          <asp:TextBox ID="TextBoxID" runat="server" CssClass="combobox
              ui-autocomplete-input ui-widget ui-widget-content ui-corner-left"></asp:TextBox>
          <!-- I know the button code is particularly nasty, no thanks to jQuery UI.
              I just copy/pasted for the most part -->
          <button id="ButtonID" type="button" tabindex="-1" title="Show All Items"
              class="toggle ui-button ui-widget ui-state-default ui-button-icon-only
              ui-corner-right ui-button-icon" role="button" aria-disabled="false"
              style="margin:0 0 0 -5px; height: 23px;">
              <span class="ui-button-icon-primary ui-icon ui-icon-triangle-1-s"></span>
              <span class="ui-button-text" style="padding:0;">&nbsp;</span>
          </button>
      </span>
      
      function cbsetup(cb, ddl) {
          try {
              $(cb).unbind();
              $(cb).autocomplete({
                  delay: 300,
                  minLength: 0,
                  autoFocus: true,
                  source: function (request, response) {
                      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                      response($(ddl).children("option").map(function () {
                          var text = $(this).text();
                          if (this.value && (!request.term || matcher.test(text)))
                              return {
                                  label: text.replace(
                                      new RegExp(
                                          "(?![^&;]+;)(?!<[^<>]*)(" +
                                          $.ui.autocomplete.escapeRegex(request.term) +
                                          ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                      ), "$1" //"<style=\"text-weight:bold;\">$1</style>"
                                      ),
                                  value: text,
                                  option: this
                              };
                      }));
                  },
                  select: function (event, ui) {
                      ui.item.option.selected = true;
                  },
                  change: function (event, ui) {
                      if (!ui.item) {
                          var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                                              valid = false;
                          select.children("option").each(function () {
                              if ($(this).text().match(matcher)) {
                                  this.selected = valid = true;
                                  return false;
                              }
                          });
                          if (!valid) {
                              // remove invalid value, as it didn't match anything
                              $(this).val("");
                              select.val("");
                              input.data("autocomplete").term = "";
                              return false;
                          }
                      }
                  }
              });
      
              $(cb).siblings("button.toggle").click(function () {
                  // close if already visible
                  if ($(cb).autocomplete("widget").is(":visible")) {
                      $(cb).autocomplete("close");
                      return;
                  }
      
                  // work around a bug (likely same cause as #5265)
                  $(this).blur();
      
                  // pass empty string as value to search for, displaying all results
                  $(cb).autocomplete("search", "");
                  $(cb).focus();
              });
          } /* TRY END */
          catch (e) { jAlert(e.name + ', ' + e.message, 'JS Exception Caught'); }
      }
      

  • 关于带有代码隐藏值 "Source:"的 jQuery 组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6821607/

    相关文章:

    javascript - 这是 jquery 3.1 中的错误吗?

    c# - 在非生产环境中测试生产配置文件

    javascript - eBay 使用 jQuery 自动完成/建议

    jquery-ui - 带有选项卡的弹出窗口 | jQuery

    javascript - 如何使用插件方法创建 Jquery 插件并保持可链接性?

    jquery - 在哪里将 Jquery Validation 插件添加到 Knockout 组件

    javascript - 在jquery中将元素置于焦点之下

    javascript - 更改区域悬停时的 img src

    c# - 让 NHibernate 在中等信任的共享主机上工作

    c# - ASP.NET Core 2.0 动态认证