简体   繁体   English

jQuery select2 v4-在选择元素上选择默认选项

[英]jquery select2 v4 - select default option on a select element

I'm using select2 v4 where I have the select2 hooked up to a <select> element using the ajax method. 我正在使用select2 v4 ,其中我使用ajax方法将select2连接到<select>元素。 All works fine except I cannot default the selected value on load. 一切正常,除非我无法在加载时默认选择的值。

The examples page says: 示例页面显示

If you need to provide default selections, you just need to include an option for each selection that contains the value and text that should be displayed. 如果需要提供默认选择,则只需为每个选择包含一个选项,其中包含应显示的值和文本。

In this code I want to default the value to "foo": 在此代码中,我想将值默认为“ foo”:

markup: 标记:

<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>

this markup is generated by my rails view (users/edit.html.erb): 这个标记是由我的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 %>

javascript in users.js.erb: 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;
}

I can see in the select2 generated markup that the span has a title attribute populated with my value but the actual span text is empty: 我可以在select2生成的标记中看到该范围具有一个填充有我的值的title属性,但实际的范围文本为空:

<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>

I have also tried the other deprecated method using initSelection to no avail: 我也尝试了使用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"});

I've also tried adding this line after also to no avail: 我也尝试过添加此行也无济于事:

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

I have looked at a bunch of answers to similar questions but they don't work for my scenario. 我看过很多类似问题的答案,但它们不适用于我的情况。 I think because I am using select2 v4 . 我认为是因为我使用的是select2 v4 Most other answers i've read say that you either need to use initSelection in combination with val - but those other examples are always using an <input> element rather than the <select> . 我读过的大多数其他答案都说,您要么需要将initSelectionval结合使用,但其他示例总是使用<input>元素而不是<select> I do note in the latest documentation that initSelection is depreciated and instead the current method of the DataAdapter should be used but I cant work out how I would apply this to my code above? 我确实在最新文档中注意到initSelectioninitSelection ,而应该使用DataAdaptercurrent方法,但是我无法弄清楚如何将其应用于上面的代码?

Not the right answer, but i had to apply a workaround - by removing the templateSelection method the problem is resolved. 不是正确的答案,但是我必须应用一种解决方法-通过删除templateSelection方法,可以解决问题。 Not a good solution though because I want the benefit of the templateSelection method. 但是,这不是一个好的解决方案,因为我想要使用templateSelection方法的好处。 I'll make do without it for now. 我暂时不要这样做。

$(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*/
  }); 
}); 

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM