如何设置jquery select2的选定值?

时间:2022-11-27 20:19:21

This belong to codes prior to select2 version 4

这属于select2版本4之前的代码

I have a simple code of select2 that get data from ajax

我有一个从ajax获取数据的select2的简单代码

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

此代码正在工作,但是,我需要在它上设置一个值,就像在编辑模式中一样。当用户第一次选择一个值时,它将被保存,当他需要编辑该值时,它必须出现在相同的select菜单(select2)中,以选择先前选择的值,但我找不到方法。

UPDATE:

更新:

The HTML code:

HTML代码:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2 programmatic access does not work with this.

Select2编程访问不能使用这个。

20 个解决方案

#1


32  

To dynamically set the "selected" value of a Select2 component:

动态设置Select2组件的“选定”值:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

Whereins the second parameter is an object with expected values.

第二个参数是具有期望值的对象。

#2


25  

SELECT2 < V4


Step #1: HTML

<input name="mySelect2" type="hidden" id="mySelect2">

Step #2: Create an instance of Select2

$("#mySelect2").select2({
      placeholder: "My Select 2",
      multiple: false,
      minimumInputLength: 1,
      ajax: {
          url: "/elements/all",
          dataType: 'json',
          quietMillis: 250,
          data: function(term, page) {
              return {
                  q: term,
              };
          },
          results: function(data, page) {
              return {results: data};
          },
          cache: true
      },
      formatResult: function(element){
          return element.text + ' (' + element.id + ')';
      },
      formatSelection: function(element){
          return element.text + ' (' + element.id + ')';
      },
      escapeMarkup: function(m) {
          return m;
      }
});

Step #3: Set your desired value

$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});

If you use select2 without AJAX you can do as follow:

如果您使用select2而不使用AJAX,可以执行以下操作:

<select name="mySelect2" id="mySelect2">
  <option value="0">One</option>
  <option value="1">Two</option>
  <option value="2">Three</option>
</select>
/* //////////// "One" will be the selected option */
$('[name=mySelect2]').val("0");

You can also do so:

你也可以这样做:

$("#mySelect2").select2("val", "0");

SELECT2 V4


For select2 v4 you can append directly an option/s as follow:

对于select2 v4,您可以直接附加一个选项/s,如下所示:

<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
    <option value="TheID" selected="selected">The text</option>                                                                   
</select>

Or with JQuery:

或与JQuery:

var $newOption = $("<option></option>").val("TheID").text("The text")

$("#myMultipleSelect2").append($newOption).trigger('change');

other example

其他的例子

$("select123455").val(5).trigger('change');

#3


11  

Html:

Html:

<select id="lang" >
   <option value="php">php</option>
   <option value="asp">asp</option>
   <option value="java">java</option>
</select>

JavaScript:

JavaScript:

$("#lang").select2().select2('val','asp');

jsfiddle

jsfiddle

#4


8  

Also as I tried, when use ajax in select2, the programmatic control methods for set new values in select2 does not work for me! Now I write these code for resolve the problem:

同样,当我尝试在select2中使用ajax时,select2中设置新值的编程控制方法对我不起作用!现在我写这些代码来解决问题:

$('#sel')
    .empty() //empty select
    .append($("<option/>") //add option tag in select
        .val("20") //set value for option to post it
        .text("nabi")) //set a text for show in select
    .val("20") //select option of select2
    .trigger("change"); //apply to select2

You can test complete sample code in here link: https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
In this sample code there is a ajax select2 and you can set new value with a button.

您可以在这里的链接中测试完整的示例代码:https://jsfiddle.net/NabiKAZ/2g1qq26v/32/在这个示例代码中有一个ajax select2,您可以使用一个按钮来设置新值。

$("#btn").click(function() {
  $('#sel')
    .empty() //empty select
    .append($("<option/>") //add option tag in select
      .val("20") //set value for option to post it
      .text("nabi")) //set a text for show in select
    .val("20") //select option of select2
    .trigger("change"); //apply to select2
});

$("#sel").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function(params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function(data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function(markup) {
    return markup;
  }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatRepo, // omitted for brevity, see the source of this page
  templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

function formatRepo(repo) {
  if (repo.loading) return repo.text;

  var markup = "<div class='select2-result-repository clearfix'>" +
    "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
    "<div class='select2-result-repository__meta'>" +
    "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

  if (repo.description) {
    markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
  }

  markup += "<div class='select2-result-repository__statistics'>" +
    "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
    "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
    "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
    "</div>" +
    "</div></div>";

  return markup;
}

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">

<select id="sel" multiple="multiple" class="col-xs-5">
</select>

<button id="btn">Set Default</button>

#5


6  

In the current version on select2 - v4.0.1 you can set the value like this:

在select2 - v4.0.1的当前版本中,可以这样设置值:

var $example = $('.js-example-programmatic').select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });

// Option 2 if you can't trigger the change event.
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />

using "trigger(change)"
<select class="js-example-programmatic">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  <optgroup label="Mountain Time Zone">
    <option value="AZ">Arizona</option>
    <option value="CO">Colorado</option>
    <option value="ID">Idaho</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NM">New Mexico</option>
    <option value="ND">North Dakota</option>
    <option value="UT">Utah</option>
    <option value="WY">Wyoming</option>
  </optgroup>
  <optgroup label="Central Time Zone">
    <option value="AL">Alabama</option>
    <option value="AR">Arkansas</option>
    <option value="IL">Illinois</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="OK">Oklahoma</option>
    <option value="SD">South Dakota</option>
    <option value="TX">Texas</option>
    <option value="TN">Tennessee</option>
    <option value="WI">Wisconsin</option>
  </optgroup>
  <optgroup label="Eastern Time Zone">
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="IN">Indiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="OH">Ohio</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WV">West Virginia</option>
  </optgroup>
</select>

using destroy: 
<select class="js-example-programmatic">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  <optgroup label="Mountain Time Zone">
    <option value="AZ">Arizona</option>
    <option value="CO">Colorado</option>
    <option value="ID">Idaho</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NM">New Mexico</option>
    <option value="ND">North Dakota</option>
    <option value="UT">Utah</option>
    <option value="WY">Wyoming</option>
  </optgroup>
  <optgroup label="Central Time Zone">
    <option value="AL">Alabama</option>
    <option value="AR">Arkansas</option>
    <option value="IL">Illinois</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="OK">Oklahoma</option>
    <option value="SD">South Dakota</option>
    <option value="TX">Texas</option>
    <option value="TN">Tennessee</option>
    <option value="WI">Wisconsin</option>
  </optgroup>
  <optgroup label="Eastern Time Zone">
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="IN">Indiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="OH">Ohio</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WV">West Virginia</option>
  </optgroup>
</select>

<button class="js-programmatic-set-val">set value</button>

#6


4  

I think you need the initSelection function

我认为你需要initSelection函数

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  initSelection: function (element, callback) {
    var id = $(element).val();
    if (id !== "") {
      $.ajax("ajax.php/get_where", {
        data: {programid: id},
        dataType: "json"
      }).done(function (data) {
        $.each(data, function (i, value) {
          callback({"text": value.text, "id": value.id});
        });
        ;
      });
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

#7


4  

var $option = $("<option selected></option>").val('1').text("Pick me");

$('#select_id').append($option).trigger('change');

Try this append then select. Doesn't duplicate the option upon AJAX call.

尝试这个附加然后选择。在AJAX调用时不重复该选项。

#8


3  

For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.

对于Ajax,使用$(“.select2”).val(" ").trigger(“改变”)。这应该能解决问题。

#9


2  

HTML

HTML

<select id="lang" >
   <option value="php">php</option>
   <option value="asp">asp</option>
   <option value="java">java</option>
</select>

JS

JS

 $("#lang").select2().val('php').trigger('change.select2');

source: https://select2.github.io/options.html

来源:https://select2.github.io/options.html

#10


2  

In Select2 V.4

在Select2 V.4

use $('selector').select2().val(value_to_select).trigger('change');

使用$(“选择器”).select2().val(value_to_select).trigger(“改变”);

I think it should work

我认为它应该奏效。

#11


0  

I did something like this to preset elements in select2 ajax dropdown

我对select2 ajax下拉菜单中的元素做了这样的设置

      //preset element values
        $(id).val(topics);
       //topics is an array of format [{"id":"","text":""}, .....]
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

#12


0  

You should use:

你应该使用:

var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');

// For set multi selected values
var data =  [];//Array Ids
var option =  [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
    // append the new option
    $("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');

    // get a list of selected values if any - or create an empty array
    var selectedValues = $("#EventId").val();
    if (selectedValues == null) {
        selectedValues = new Array();
    }
    selectedValues.push(response.id);   // add the newly created option to the list of selected items
    $("#EventId").val(selectedValues).trigger('change');   // have select2 do it's thing
});

#13


0  

An Phan's answer worked for me:

安潘的回答对我起了作用:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

But adding the change trigger the event

但是添加更改触发事件。

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change();

#14


0  

If you are using an Input box, you must set the "multiple" property with its value as "true". For example,

如果使用输入框,则必须将“多个”属性设置为“true”。例如,

<script>
    $(document).ready(function () {

        var arr = [{ id: 100, text: 'Lorem Ipsum 1' },
            { id: 200, text: 'Lorem Ipsum 2'}];

        $('#inputID').select2({
            data: arr,
            width: 200,
            multiple: true
        });
    });
</script>

#15


0  

In select2 < version4 there is the option initSelection() for remote data loading, through which it is possible to set initial value for the input as in edit mode.

在select2 < version4中,有一个选项initSelection()用于远程数据加载,通过该选项可以将输入的初始值设置为编辑模式。

$("#e6").select2({
    placeholder: "Search for a repository",
    minimumInputLength: 1,
    ajax: { 
        // instead of writing the function to execute the request we use Select2's convenient helper
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        quietMillis: 250,
        data: function (term, page) {
            return {
                q: term, // search term
            };
        },
        results: function (data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter the remote JSON data
            return { results: data.items };
        },
        cache: true
    },
    initSelection: function(element, callback) {
        // the input tag has a value attribute preloaded that points to a preselected repository's id
        // this function resolves that id attribute to an object that select2 can render
        // using its formatResult renderer - that way the repository name is shown preselected
        var id = $(element).val();
        if (id !== "") {
            $.ajax("https://api.github.com/repositories/" + id, {
                dataType: "json"
            }).done(function(data) { callback(data); });
        }
    },
    formatResult: repoFormatResult, // omitted for brevity, see the source of this page
    formatSelection: repoFormatSelection,  // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

Source Documentation : Select2 - 3.5.3

源文档:Select2 - 3.5.3

#16


0  

Sometimes, select2() will be loading firstly, and that makes the control not to show previously selected value correctly. Putting a delay for some seconds can resolve this problem.

有时,select2()将首先加载,这使得控件不能正确显示先前选择的值。延迟几秒钟可以解决这个问题。

setTimeout(function(){                  
    $('#costcentreid').select2();               
},3000);

#17


0  

Just to add to anyone else who may have come up with the same issue with me.

我只是想补充一下其他可能和我有同样问题的人。

I was trying to set the selected option of my dynamically loaded options (from AJAX) and was trying to set one of the options as selected depending on some logic.

我试图设置我的动态加载选项(来自AJAX)的选择选项,并试图根据某些逻辑设置其中一个选项。

My issue came because I wasn't trying to set the selected option based on the ID which needs to match the value, not the value matching the name!

我的问题来了,因为我没有尝试根据需要匹配值的ID来设置所选的选项,而不是匹配名称的值!

#18


0  

I did like this-

我做了这样的-

$("#drpServices").select2().val("0").trigger("change");

#19


-1  

You can use this code:

您可以使用以下代码:

    $('#country').select2("val", "Pakistan").trigger('change');

Put your desired value instead of Pakistan

把你想要的价值,而不是巴基斯坦

Hope It will work :)

希望它能起作用:)

#20


-1  

Nice and easy:

很简单:

document.getElementById("select2-id_city-container").innerHTML = "Your Text Here";

And you change id_city to your select's id.

然后将id_city更改为select的id。

Edit: After Glen's comment I realize I should explain why and how it worked for me:

编辑:在格伦的评论之后,我意识到我应该解释为什么,以及它是如何为我工作的:

I had made select2 working really nice for my form. The only thing I couldn't make work was to show the current selected value when editing. It was searching a third party API, saving new and editing old records. After a while I realized I didn't need to set the value correctly, only the label inside field, because if the user doesn't change the field, nothing happens. After searching and looking to a lot of people having trouble with it, I decided make it with pure Javascript. It worked and I posted to maybe help someone. I also suggest to set a timer for it.

我让select2在我的表单上运行得非常好。我惟一做不到的就是在编辑时显示当前选定的值。它正在搜索一个第三方API,保存新记录并编辑旧记录。过了一会儿,我意识到我不需要正确地设置值,只需要在字段内设置标签,因为如果用户不更改字段,就不会发生任何事情。在搜索和查找了很多有问题的人之后,我决定用纯Javascript做它。它起作用了,我发帖子可能是为了帮助别人。我还建议为它设置一个计时器。

#1


32  

To dynamically set the "selected" value of a Select2 component:

动态设置Select2组件的“选定”值:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

Whereins the second parameter is an object with expected values.

第二个参数是具有期望值的对象。

#2


25  

SELECT2 < V4


Step #1: HTML

<input name="mySelect2" type="hidden" id="mySelect2">

Step #2: Create an instance of Select2

$("#mySelect2").select2({
      placeholder: "My Select 2",
      multiple: false,
      minimumInputLength: 1,
      ajax: {
          url: "/elements/all",
          dataType: 'json',
          quietMillis: 250,
          data: function(term, page) {
              return {
                  q: term,
              };
          },
          results: function(data, page) {
              return {results: data};
          },
          cache: true
      },
      formatResult: function(element){
          return element.text + ' (' + element.id + ')';
      },
      formatSelection: function(element){
          return element.text + ' (' + element.id + ')';
      },
      escapeMarkup: function(m) {
          return m;
      }
});

Step #3: Set your desired value

$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});

If you use select2 without AJAX you can do as follow:

如果您使用select2而不使用AJAX,可以执行以下操作:

<select name="mySelect2" id="mySelect2">
  <option value="0">One</option>
  <option value="1">Two</option>
  <option value="2">Three</option>
</select>
/* //////////// "One" will be the selected option */
$('[name=mySelect2]').val("0");

You can also do so:

你也可以这样做:

$("#mySelect2").select2("val", "0");

SELECT2 V4


For select2 v4 you can append directly an option/s as follow:

对于select2 v4,您可以直接附加一个选项/s,如下所示:

<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
    <option value="TheID" selected="selected">The text</option>                                                                   
</select>

Or with JQuery:

或与JQuery:

var $newOption = $("<option></option>").val("TheID").text("The text")

$("#myMultipleSelect2").append($newOption).trigger('change');

other example

其他的例子

$("select123455").val(5).trigger('change');

#3


11  

Html:

Html:

<select id="lang" >
   <option value="php">php</option>
   <option value="asp">asp</option>
   <option value="java">java</option>
</select>

JavaScript:

JavaScript:

$("#lang").select2().select2('val','asp');

jsfiddle

jsfiddle

#4


8  

Also as I tried, when use ajax in select2, the programmatic control methods for set new values in select2 does not work for me! Now I write these code for resolve the problem:

同样,当我尝试在select2中使用ajax时,select2中设置新值的编程控制方法对我不起作用!现在我写这些代码来解决问题:

$('#sel')
    .empty() //empty select
    .append($("<option/>") //add option tag in select
        .val("20") //set value for option to post it
        .text("nabi")) //set a text for show in select
    .val("20") //select option of select2
    .trigger("change"); //apply to select2

You can test complete sample code in here link: https://jsfiddle.net/NabiKAZ/2g1qq26v/32/
In this sample code there is a ajax select2 and you can set new value with a button.

您可以在这里的链接中测试完整的示例代码:https://jsfiddle.net/NabiKAZ/2g1qq26v/32/在这个示例代码中有一个ajax select2,您可以使用一个按钮来设置新值。

$("#btn").click(function() {
  $('#sel')
    .empty() //empty select
    .append($("<option/>") //add option tag in select
      .val("20") //set value for option to post it
      .text("nabi")) //set a text for show in select
    .val("20") //select option of select2
    .trigger("change"); //apply to select2
});

$("#sel").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function(params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function(data, params) {
      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function(markup) {
    return markup;
  }, // let our custom formatter work
  minimumInputLength: 1,
  templateResult: formatRepo, // omitted for brevity, see the source of this page
  templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

function formatRepo(repo) {
  if (repo.loading) return repo.text;

  var markup = "<div class='select2-result-repository clearfix'>" +
    "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
    "<div class='select2-result-repository__meta'>" +
    "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

  if (repo.description) {
    markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
  }

  markup += "<div class='select2-result-repository__statistics'>" +
    "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +
    "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +
    "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +
    "</div>" +
    "</div></div>";

  return markup;
}

function formatRepoSelection(repo) {
  return repo.full_name || repo.text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">

<select id="sel" multiple="multiple" class="col-xs-5">
</select>

<button id="btn">Set Default</button>

#5


6  

In the current version on select2 - v4.0.1 you can set the value like this:

在select2 - v4.0.1的当前版本中,可以这样设置值:

var $example = $('.js-example-programmatic').select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });

// Option 2 if you can't trigger the change event.
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />

using "trigger(change)"
<select class="js-example-programmatic">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  <optgroup label="Mountain Time Zone">
    <option value="AZ">Arizona</option>
    <option value="CO">Colorado</option>
    <option value="ID">Idaho</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NM">New Mexico</option>
    <option value="ND">North Dakota</option>
    <option value="UT">Utah</option>
    <option value="WY">Wyoming</option>
  </optgroup>
  <optgroup label="Central Time Zone">
    <option value="AL">Alabama</option>
    <option value="AR">Arkansas</option>
    <option value="IL">Illinois</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="OK">Oklahoma</option>
    <option value="SD">South Dakota</option>
    <option value="TX">Texas</option>
    <option value="TN">Tennessee</option>
    <option value="WI">Wisconsin</option>
  </optgroup>
  <optgroup label="Eastern Time Zone">
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="IN">Indiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="OH">Ohio</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WV">West Virginia</option>
  </optgroup>
</select>

using destroy: 
<select class="js-example-programmatic">
  <optgroup label="Alaskan/Hawaiian Time Zone">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
  </optgroup>
  <optgroup label="Pacific Time Zone">
    <option value="CA">California</option>
    <option value="NV">Nevada</option>
    <option value="OR">Oregon</option>
    <option value="WA">Washington</option>
  </optgroup>
  <optgroup label="Mountain Time Zone">
    <option value="AZ">Arizona</option>
    <option value="CO">Colorado</option>
    <option value="ID">Idaho</option>
    <option value="MT">Montana</option>
    <option value="NE">Nebraska</option>
    <option value="NM">New Mexico</option>
    <option value="ND">North Dakota</option>
    <option value="UT">Utah</option>
    <option value="WY">Wyoming</option>
  </optgroup>
  <optgroup label="Central Time Zone">
    <option value="AL">Alabama</option>
    <option value="AR">Arkansas</option>
    <option value="IL">Illinois</option>
    <option value="IA">Iowa</option>
    <option value="KS">Kansas</option>
    <option value="KY">Kentucky</option>
    <option value="LA">Louisiana</option>
    <option value="MN">Minnesota</option>
    <option value="MS">Mississippi</option>
    <option value="MO">Missouri</option>
    <option value="OK">Oklahoma</option>
    <option value="SD">South Dakota</option>
    <option value="TX">Texas</option>
    <option value="TN">Tennessee</option>
    <option value="WI">Wisconsin</option>
  </optgroup>
  <optgroup label="Eastern Time Zone">
    <option value="CT">Connecticut</option>
    <option value="DE">Delaware</option>
    <option value="FL">Florida</option>
    <option value="GA">Georgia</option>
    <option value="IN">Indiana</option>
    <option value="ME">Maine</option>
    <option value="MD">Maryland</option>
    <option value="MA">Massachusetts</option>
    <option value="MI">Michigan</option>
    <option value="NH">New Hampshire</option>
    <option value="NJ">New Jersey</option>
    <option value="NY">New York</option>
    <option value="NC">North Carolina</option>
    <option value="OH">Ohio</option>
    <option value="PA">Pennsylvania</option>
    <option value="RI">Rhode Island</option>
    <option value="SC">South Carolina</option>
    <option value="VT">Vermont</option>
    <option value="VA">Virginia</option>
    <option value="WV">West Virginia</option>
  </optgroup>
</select>

<button class="js-programmatic-set-val">set value</button>

#6


4  

I think you need the initSelection function

我认为你需要initSelection函数

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  initSelection: function (element, callback) {
    var id = $(element).val();
    if (id !== "") {
      $.ajax("ajax.php/get_where", {
        data: {programid: id},
        dataType: "json"
      }).done(function (data) {
        $.each(data, function (i, value) {
          callback({"text": value.text, "id": value.id});
        });
        ;
      });
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

#7


4  

var $option = $("<option selected></option>").val('1').text("Pick me");

$('#select_id').append($option).trigger('change');

Try this append then select. Doesn't duplicate the option upon AJAX call.

尝试这个附加然后选择。在AJAX调用时不重复该选项。

#8


3  

For Ajax, use $(".select2").val("").trigger("change"). That should solve the problem.

对于Ajax,使用$(“.select2”).val(" ").trigger(“改变”)。这应该能解决问题。

#9


2  

HTML

HTML

<select id="lang" >
   <option value="php">php</option>
   <option value="asp">asp</option>
   <option value="java">java</option>
</select>

JS

JS

 $("#lang").select2().val('php').trigger('change.select2');

source: https://select2.github.io/options.html

来源:https://select2.github.io/options.html

#10


2  

In Select2 V.4

在Select2 V.4

use $('selector').select2().val(value_to_select).trigger('change');

使用$(“选择器”).select2().val(value_to_select).trigger(“改变”);

I think it should work

我认为它应该奏效。

#11


0  

I did something like this to preset elements in select2 ajax dropdown

我对select2 ajax下拉菜单中的元素做了这样的设置

      //preset element values
        $(id).val(topics);
       //topics is an array of format [{"id":"","text":""}, .....]
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

#12


0  

You should use:

你应该使用:

var autocompleteIds= $("#EventId");
autocompleteIds.empty().append('<option value="Id">Text</option>').val("Id").trigger('change');

// For set multi selected values
var data =  [];//Array Ids
var option =  [];//Array options of Ids above
autocompleteIds.empty().append(option).val(data).trigger('change');

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
    // append the new option
    $("#EventId").append('<option value="' + response.id + '">' + response.text + '</option>');

    // get a list of selected values if any - or create an empty array
    var selectedValues = $("#EventId").val();
    if (selectedValues == null) {
        selectedValues = new Array();
    }
    selectedValues.push(response.id);   // add the newly created option to the list of selected items
    $("#EventId").val(selectedValues).trigger('change');   // have select2 do it's thing
});

#13


0  

An Phan's answer worked for me:

安潘的回答对我起了作用:

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});

But adding the change trigger the event

但是添加更改触发事件。

$('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'}).change();

#14


0  

If you are using an Input box, you must set the "multiple" property with its value as "true". For example,

如果使用输入框,则必须将“多个”属性设置为“true”。例如,

<script>
    $(document).ready(function () {

        var arr = [{ id: 100, text: 'Lorem Ipsum 1' },
            { id: 200, text: 'Lorem Ipsum 2'}];

        $('#inputID').select2({
            data: arr,
            width: 200,
            multiple: true
        });
    });
</script>

#15


0  

In select2 < version4 there is the option initSelection() for remote data loading, through which it is possible to set initial value for the input as in edit mode.

在select2 < version4中,有一个选项initSelection()用于远程数据加载,通过该选项可以将输入的初始值设置为编辑模式。

$("#e6").select2({
    placeholder: "Search for a repository",
    minimumInputLength: 1,
    ajax: { 
        // instead of writing the function to execute the request we use Select2's convenient helper
        url: "https://api.github.com/search/repositories",
        dataType: 'json',
        quietMillis: 250,
        data: function (term, page) {
            return {
                q: term, // search term
            };
        },
        results: function (data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter the remote JSON data
            return { results: data.items };
        },
        cache: true
    },
    initSelection: function(element, callback) {
        // the input tag has a value attribute preloaded that points to a preselected repository's id
        // this function resolves that id attribute to an object that select2 can render
        // using its formatResult renderer - that way the repository name is shown preselected
        var id = $(element).val();
        if (id !== "") {
            $.ajax("https://api.github.com/repositories/" + id, {
                dataType: "json"
            }).done(function(data) { callback(data); });
        }
    },
    formatResult: repoFormatResult, // omitted for brevity, see the source of this page
    formatSelection: repoFormatSelection,  // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

Source Documentation : Select2 - 3.5.3

源文档:Select2 - 3.5.3

#16


0  

Sometimes, select2() will be loading firstly, and that makes the control not to show previously selected value correctly. Putting a delay for some seconds can resolve this problem.

有时,select2()将首先加载,这使得控件不能正确显示先前选择的值。延迟几秒钟可以解决这个问题。

setTimeout(function(){                  
    $('#costcentreid').select2();               
},3000);

#17


0  

Just to add to anyone else who may have come up with the same issue with me.

我只是想补充一下其他可能和我有同样问题的人。

I was trying to set the selected option of my dynamically loaded options (from AJAX) and was trying to set one of the options as selected depending on some logic.

我试图设置我的动态加载选项(来自AJAX)的选择选项,并试图根据某些逻辑设置其中一个选项。

My issue came because I wasn't trying to set the selected option based on the ID which needs to match the value, not the value matching the name!

我的问题来了,因为我没有尝试根据需要匹配值的ID来设置所选的选项,而不是匹配名称的值!

#18


0  

I did like this-

我做了这样的-

$("#drpServices").select2().val("0").trigger("change");

#19


-1  

You can use this code:

您可以使用以下代码:

    $('#country').select2("val", "Pakistan").trigger('change');

Put your desired value instead of Pakistan

把你想要的价值,而不是巴基斯坦

Hope It will work :)

希望它能起作用:)

#20


-1  

Nice and easy:

很简单:

document.getElementById("select2-id_city-container").innerHTML = "Your Text Here";

And you change id_city to your select's id.

然后将id_city更改为select的id。

Edit: After Glen's comment I realize I should explain why and how it worked for me:

编辑:在格伦的评论之后,我意识到我应该解释为什么,以及它是如何为我工作的:

I had made select2 working really nice for my form. The only thing I couldn't make work was to show the current selected value when editing. It was searching a third party API, saving new and editing old records. After a while I realized I didn't need to set the value correctly, only the label inside field, because if the user doesn't change the field, nothing happens. After searching and looking to a lot of people having trouble with it, I decided make it with pure Javascript. It worked and I posted to maybe help someone. I also suggest to set a timer for it.

我让select2在我的表单上运行得非常好。我惟一做不到的就是在编辑时显示当前选定的值。它正在搜索一个第三方API,保存新记录并编辑旧记录。过了一会儿,我意识到我不需要正确地设置值,只需要在字段内设置标签,因为如果用户不更改字段,就不会发生任何事情。在搜索和查找了很多有问题的人之后,我决定用纯Javascript做它。它起作用了,我发帖子可能是为了帮助别人。我还建议为它设置一个计时器。