简体   繁体   English

如何使用 initSelection 设置 Select2 值?

[英]How to set Select2 value using initSelection?

I am using jQuery Select2 for dropdown lists.我使用 jQuery Select2 作为下拉列表。 The data is loading via AJAX call using in JSON format.数据通过 AJAX 调用以 JSON 格式加载。

Here is my script:这是我的脚本:

$("#sub_lessons").select2({ 
     maximumSelectionSize: 1,
     placeholder: "Select Sublessons",
     allowClear: true,
     multiple:true,
        ajax: {
          url: "getData.action?lid="+lessonid,   
          dataType: 'json',
          data: function (term, page) {
            return {
              q: term
            };
          },
          results: function (data, page) {
            return { results: data };

          }
        } 
    }); 

My html snippet:我的 html 片段:

<input type="hidden" id="sub_lessons" style="width:300px"/>

When we clicking on the select2 box the data is loading perfectly, but I have the function like setValue() when button is clicked.当我们单击 select2 框时,数据正在完美加载,但是当单击按钮时,我有像 setValue() 这样的函数。

<input type="button" onclick="setValue(1)"/>

And my function is:我的功能是:

function setValue(no)
{
 $('#sub_lessons').select2('val',no);
}

But the value is not being set.但是没有设置该值。 I searched in some sites and suggested to use initselection.I used initselection,but it does not work.please help me how to set value to select2 when button is pressed.我在一些网站上搜索并建议使用 initselection。我使用了 initselection,但它不起作用。请帮助我如何在按下按钮时将值设置为 select2。

any help would be appreciated.任何帮助,将不胜感激。

尝试这样的事情

$('#sub_lessons').select2('val','no');

I try this;我试试这个; work for me.为我工作。 You should add this to initSelection select2:您应该将其添加到 initSelection select2:

        initSelection: function (element, callback) {
        var id = $(element).val();
        $.ajax("url/" + id, {
            dataType: "json"
        }).done(function (data) {
            var newOption = new Option(data.title, data.id, true, true);
            $('#sub_lessons').append(newOption).trigger('change');
            callback({"text": data.title, "id": data.id});
        });
    },

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

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