简体   繁体   中英

How to set Select2 value using initSelection?

I am using jQuery Select2 for dropdown lists. The data is loading via AJAX call using in JSON format.

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:

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

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

any help would be appreciated.

尝试这样的事情

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

I try this; work for me. You should add this to 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});
        });
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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