jquery select2 v4 - 选择元素

时间:2015-08-21 06:56:42

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

我使用select2 v4使用ajax方法将select2连接到<select>元素。一切正常,但我无法在加载时默认选定的值。

examples page说:

  

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

在此代码中,我想将值默认为&#34; foo&#34;:

标记:

<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结合使用 - 但其他示例总是使用<input>元素而不是{{1} }}。我在最新文档中注意到<select>已弃用,而应使用DataAdapterinitSelection方法但我无法弄清楚如何将其应用于上面的代码?< / p>

2 个答案:

答案 0 :(得分:2)

不是正确的答案,但我必须应用解决方法 - 通过删除问题解决的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*/
  }); 
}); 

答案 1 :(得分:0)

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

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