【问题标题】:Load options in Select2 after entering partial text in select box through jQuery通过jQuery在选择框中输入部分文本后在Select2中加载选项
【发布时间】:2017-02-13 12:31:28
【问题描述】:

在 Select2 中,我想选择一个选项 india。我开始在选择框中输入两个字母in。之后,我想通过jQuery从数据库中加载选项标签中的相关数据。我该怎么做?

【问题讨论】:

    标签: jquery jquery-plugins select2


    【解决方案1】:

    对于您的示例,您可以查找此解决方案:http://jqueryui.com/autocomplete/

    除此之外,您还可以使用 Jquery 自动完成功能。

    除此之外,您还可以编写自己的函数,该函数将在输入文本的 keydown 时将选择查询发送到您的数据库,并获取相关列表以附加到选择框中。

    【讨论】:

    • 感谢@nikhil kumar 的即时回复.. 但我希望输入字段必须是选择字段..(尤其是 select2)。
    【解决方案2】:

    您是否使用 2 个 select2 下拉菜单?如果是,那么在更改第一个选择下拉列表时,您将使用 AJAX 获取相关数据并将其加载到您的目标 select2 下拉列表中,将结果对象作为“数据”属性传递,同时为其初始化 select2。

    如果这不是您想要的,请详细说明您的问题。

    【讨论】:

    • 不使用依赖下拉菜单。我希望 select2 字段作为自动完成。在我在 select2 搜索字段中键入两个字母后,自动完成将通过选择选项触发。
    【解决方案3】:

    我想出了解决方案@https://select2.github.io/examples.html#data-ajax

    HTML 部分:

    <select class="js-data-example-ajax">
      <option value="3620194" selected="selected">select2/select2</option>
    </select>
    

    JQUERY 部分:

    $(".js-data-example-ajax").select2({
      ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;
    
      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
      },
      escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
      minimumInputLength: 1,
      templateResult: formatRepo, // omitted for brevity, see the source of this page
      templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多