【问题标题】:jquery select2 v4 - select default option on a select elementjquery select2 v4 - 在选择元素上选择默认选项
【发布时间】:2015-11-15 00:52:01
【问题描述】:

我正在使用select2 v4,其中我使用ajax 方法将select2 连接到<select> 元素。一切正常,除了我不能默认加载时选择的值。

examples page 说:

如果您需要提供默认选择,您只需为每个选择包含一个选项,其中包含应显示的值和文本。

在这段代码中,我想将值默认为“foo”:

标记:

<label class="input">
  <select aria-hidden="true" tabindex="-1" 
    class="form-control user-school-select select2-hidden-accessible" 
    name="user[school_id]" id="user_school_id">
    <option selected="selected" value="1">foo</option>
  </select>
  <span style="width: 372px;" dir="ltr" 
    class="select2 select2-container select2-container--default">
    <span class="selection">
      <span aria-labelledby="select2-user_school_id-container" 
        tabindex="0" class="select2-selection select2-selection--single" 
        role="combobox" aria-autocomplete="list" aria-haspopup="true" 
        aria-expanded="false">
          <span title="foo" id="select2-user_school_id-container" 
            class="select2-selection__rendered"></span>
          <span class="select2-selection__arrow" role="presentation">
            <b role="presentation"></b></span></span></span>
 <span class="dropdown-wrapper" aria-hidden="true"></span></span></span>
</label>

这个标记是由我的 rails 视图 (users/edit.html.erb) 生成的:

<%= label_tag nil, nil, :class => "input" do %>
  <% if @user.school_id %>
    <%= f.select :school_id, 
                 options_for_select({ @user.user_school => @user.school_id }, @user.school_id ), {}, 
                 { class: "form-control user-school-select" } %>
  <% else %>
    <%= f.select :school_id, {}, {},
                 {class: "form-control user-school-select"} %>
  <% end %>
<% end %>

users.js.erb 中的javascript:

$(document).ready(function() {
  $(".user-school-select").select2({
    ajax: {
        url: "/schools",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    escapeMarkup: function (markup) { return markup; }, 
    minimumInputLength: 2,
    templateResult: formatSchool,
    templateSelection: formatSchoolSelection
  }); 
});  

function formatSchool (school) {
  var markup = '<div class="clearfix">' +
        '<div class="col-sm-1">' +
        (school.logo_url ? '<img src="' + school.logo_url + '" style="max-width: 100%" />' : "") +
        '</div>' +
        '<div class="col-sm-10">' +
        '<div class="clearfix">' +
        '<div class="col-sm-9">' + school.name + '</div>' +
        '</div>';
  markup += '</div></div>';
  return markup;
} 

function formatSchoolSelection (school) {
  return school.name;
}

我可以在 select2 生成的标记中看到 span 有一个 title 属性填充了我的值,但实际的 span 文本是空的:

<span class="selection">
  <span aria-labelledby="select2-user_school_id-container" tabindex="0" 
    class="select2-selection select2-selection--single" 
    role="combobox" aria-autocomplete="list" aria-haspopup="true" 
    aria-expanded="false">
    <span title="foo" id="select2-user_school_id-container" 
      class="select2-selection__rendered"></span>
    <span class="select2-selection__arrow" role="presentation">
      <b role="presentation"></b></span></span></span>

我也尝试过使用initSelection 的其他已弃用方法,但无济于事:

$(".user-school-select").select2({
    ajax: {
        url: "/schools",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 2,
    templateResult: formatSchool,
    templateSelection: formatSchoolSelection,
    initSelection : function (element, callback) {
        var data = {"id":"1","text":'foo'};
        callback(data);
    }
});
$(".user-school-select").select2("data", {"id": 1, "text": "foo"});

我也试过添加这一行也无济于事:

$(".user-school-select").select2("val", "1");

我查看了许多类似问题的答案,但它们不适用于我的场景。我想是因为我使用的是select2 v4。我读过的大多数其他答案都说您需要将initSelectionval 结合使用-但其他示例始终使用&lt;input&gt; 元素而不是&lt;select&gt;。我在最新文档中确实注意到initSelection 已被贬值,而应该使用DataAdaptercurrent 方法,但我不知道如何将它应用到我上面的代码中?

【问题讨论】:

    标签: javascript jquery ruby-on-rails jquery-select2 jquery-select2-4


    【解决方案1】:

    不是正确的答案,但我必须采用一种解决方法 - 通过删除 templateSelection 方法问题得到解决。虽然不是一个好的解决方案,因为我想要 templateSelection 方法的好处。我暂时不用它。

    $(document).ready(function() {
      $(".user-school-select").select2({
        ajax: {
            url: "/schools",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, page) {
                return {
                    results: data
                };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, 
        minimumInputLength: 2,
        templateResult: formatSchool/*,
        templateSelection: formatSchoolSelection*/
      }); 
    }); 
    

    【讨论】:

    • 您可以在formatSchoolSelection:function(item) { return item.text || yourcustomcodehere; } 中执行此操作。选定的值将作为包含idtext 键的对象通过templateSelect
    【解决方案2】:

    设置如下值后,尝试在select2 上触发change

    $(".user-school-select").select2("val", "1").trigger('change');
    

    【讨论】:

    • 它对我不起作用,当我尝试你的建议时它给了我错误:TypeError: $(...).select2(...) is undefined 当我尝试这个时它没有错误但没有修复:$(".user-school-select").select2("val", "1"); $(".user-school-select").trigger("change");
    • 当然,它在 Rails 应用程序中,我会用更多信息更新我的问题
    • 我更新了我的代码以提供更多上下文,我不知道我还能提供多少帮助?感谢您的帮助!
    • @joshweir 在您的代码中,您在哪里保留了我的答案中给出的行?
    • 我现在添加了,那行代码在上面描述的注释中给出了错误..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2017-12-18
    • 2019-04-19
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多