[javascript] How to set selected value of jquery select2?

This belong to codes prior to select2 version 4

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

$("#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.

UPDATE:

The HTML code:

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

Select2 programmatic access does not work with this.

This question is related to javascript php jquery ajax jquery-select2

The answer is


Nice and easy:

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

And you change id_city to your select's 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.


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:

$('#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.

_x000D_
_x000D_
$("#btn").click(function() {_x000D_
  $('#sel')_x000D_
    .empty() //empty select_x000D_
    .append($("<option/>") //add option tag in select_x000D_
      .val("20") //set value for option to post it_x000D_
      .text("nabi")) //set a text for show in select_x000D_
    .val("20") //select option of select2_x000D_
    .trigger("change"); //apply to select2_x000D_
});_x000D_
_x000D_
$("#sel").select2({_x000D_
  ajax: {_x000D_
    url: "https://api.github.com/search/repositories",_x000D_
    dataType: 'json',_x000D_
    delay: 250,_x000D_
    data: function(params) {_x000D_
      return {_x000D_
        q: params.term, // search term_x000D_
        page: params.page_x000D_
      };_x000D_
    },_x000D_
    processResults: function(data, params) {_x000D_
      // parse the results into the format expected by Select2_x000D_
      // since we are using custom formatting functions we do not need to_x000D_
      // alter the remote JSON data, except to indicate that infinite_x000D_
      // scrolling can be used_x000D_
      params.page = params.page || 1;_x000D_
_x000D_
      return {_x000D_
        results: data.items,_x000D_
        pagination: {_x000D_
          more: (params.page * 30) < data.total_count_x000D_
        }_x000D_
      };_x000D_
    },_x000D_
    cache: true_x000D_
  },_x000D_
  escapeMarkup: function(markup) {_x000D_
    return markup;_x000D_
  }, // let our custom formatter work_x000D_
  minimumInputLength: 1,_x000D_
  templateResult: formatRepo, // omitted for brevity, see the source of this page_x000D_
  templateSelection: formatRepoSelection // omitted for brevity, see the source of this page_x000D_
});_x000D_
_x000D_
function formatRepo(repo) {_x000D_
  if (repo.loading) return repo.text;_x000D_
_x000D_
  var markup = "<div class='select2-result-repository clearfix'>" +_x000D_
    "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +_x000D_
    "<div class='select2-result-repository__meta'>" +_x000D_
    "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";_x000D_
_x000D_
  if (repo.description) {_x000D_
    markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";_x000D_
  }_x000D_
_x000D_
  markup += "<div class='select2-result-repository__statistics'>" +_x000D_
    "<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + repo.forks_count + " Forks</div>" +_x000D_
    "<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + repo.stargazers_count + " Stars</div>" +_x000D_
    "<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + repo.watchers_count + " Watchers</div>" +_x000D_
    "</div>" +_x000D_
    "</div></div>";_x000D_
_x000D_
  return markup;_x000D_
}_x000D_
_x000D_
function formatRepoSelection(repo) {_x000D_
  return repo.full_name || repo.text;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://select2.org/assets/a7be624d756ba99faa354e455aed250d.css">_x000D_
_x000D_
<select id="sel" multiple="multiple" class="col-xs-5">_x000D_
</select>_x000D_
_x000D_
<button id="btn">Set Default</button>
_x000D_
_x000D_
_x000D_


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

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

$('#inputID').val("100").select2();

It would be more appropriate to apply select2 after choosing one of the current select.


Set the value and trigger the change event immediately.

$('#selectteam').val([183,182]).trigger('change');

I use select2 with ajax source with Laravel. In my case it simple work cycling option i receive from page and add Option to select2..

$filtri->stato = [1,2,...];

$('#stato') is my select2 with server side load

<script>
    @foreach ($filtri->stato as $item)
       $('#stato').append(new Option("{{\App\Models\stato::find($item)->nome}}",{{$item}}, false, true));
    @endforeach
</script>

In my case I can call text of option with find method, but it's possible do it with ajax call


    $("#select_location_id").val(value);
    $("#select_location_id").select2().trigger('change');

I solved my problem with this simple code. Where #select_location_id is an ID of select box and value is value of an option listed in select2 box.


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

_x000D_
_x000D_
var $example = $('.js-example-programmatic').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });_x000D_
_x000D_
// Option 2 if you can't trigger the change event._x000D_
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />_x000D_
_x000D_
using "trigger(change)"_x000D_
<select class="js-example-programmatic">_x000D_
  <optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Pacific Time Zone">_x000D_
    <option value="CA">California</option>_x000D_
    <option value="NV">Nevada</option>_x000D_
    <option value="OR">Oregon</option>_x000D_
    <option value="WA">Washington</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Mountain Time Zone">_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="MT">Montana</option>_x000D_
    <option value="NE">Nebraska</option>_x000D_
    <option value="NM">New Mexico</option>_x000D_
    <option value="ND">North Dakota</option>_x000D_
    <option value="UT">Utah</option>_x000D_
    <option value="WY">Wyoming</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Central Time Zone">_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IA">Iowa</option>_x000D_
    <option value="KS">Kansas</option>_x000D_
    <option value="KY">Kentucky</option>_x000D_
    <option value="LA">Louisiana</option>_x000D_
    <option value="MN">Minnesota</option>_x000D_
    <option value="MS">Mississippi</option>_x000D_
    <option value="MO">Missouri</option>_x000D_
    <option value="OK">Oklahoma</option>_x000D_
    <option value="SD">South Dakota</option>_x000D_
    <option value="TX">Texas</option>_x000D_
    <option value="TN">Tennessee</option>_x000D_
    <option value="WI">Wisconsin</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Eastern Time Zone">_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
    <option value="ME">Maine</option>_x000D_
    <option value="MD">Maryland</option>_x000D_
    <option value="MA">Massachusetts</option>_x000D_
    <option value="MI">Michigan</option>_x000D_
    <option value="NH">New Hampshire</option>_x000D_
    <option value="NJ">New Jersey</option>_x000D_
    <option value="NY">New York</option>_x000D_
    <option value="NC">North Carolina</option>_x000D_
    <option value="OH">Ohio</option>_x000D_
    <option value="PA">Pennsylvania</option>_x000D_
    <option value="RI">Rhode Island</option>_x000D_
    <option value="SC">South Carolina</option>_x000D_
    <option value="VT">Vermont</option>_x000D_
    <option value="VA">Virginia</option>_x000D_
    <option value="WV">West Virginia</option>_x000D_
  </optgroup>_x000D_
</select>_x000D_
_x000D_
using destroy: _x000D_
<select class="js-example-programmatic">_x000D_
  <optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Pacific Time Zone">_x000D_
    <option value="CA">California</option>_x000D_
    <option value="NV">Nevada</option>_x000D_
    <option value="OR">Oregon</option>_x000D_
    <option value="WA">Washington</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Mountain Time Zone">_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="MT">Montana</option>_x000D_
    <option value="NE">Nebraska</option>_x000D_
    <option value="NM">New Mexico</option>_x000D_
    <option value="ND">North Dakota</option>_x000D_
    <option value="UT">Utah</option>_x000D_
    <option value="WY">Wyoming</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Central Time Zone">_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IA">Iowa</option>_x000D_
    <option value="KS">Kansas</option>_x000D_
    <option value="KY">Kentucky</option>_x000D_
    <option value="LA">Louisiana</option>_x000D_
    <option value="MN">Minnesota</option>_x000D_
    <option value="MS">Mississippi</option>_x000D_
    <option value="MO">Missouri</option>_x000D_
    <option value="OK">Oklahoma</option>_x000D_
    <option value="SD">South Dakota</option>_x000D_
    <option value="TX">Texas</option>_x000D_
    <option value="TN">Tennessee</option>_x000D_
    <option value="WI">Wisconsin</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Eastern Time Zone">_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
    <option value="ME">Maine</option>_x000D_
    <option value="MD">Maryland</option>_x000D_
    <option value="MA">Massachusetts</option>_x000D_
    <option value="MI">Michigan</option>_x000D_
    <option value="NH">New Hampshire</option>_x000D_
    <option value="NJ">New Jersey</option>_x000D_
    <option value="NY">New York</option>_x000D_
    <option value="NC">North Carolina</option>_x000D_
    <option value="OH">Ohio</option>_x000D_
    <option value="PA">Pennsylvania</option>_x000D_
    <option value="RI">Rhode Island</option>_x000D_
    <option value="SC">South Carolina</option>_x000D_
    <option value="VT">Vermont</option>_x000D_
    <option value="VA">Virginia</option>_x000D_
    <option value="WV">West Virginia</option>_x000D_
  </optgroup>_x000D_
</select>_x000D_
_x000D_
<button class="js-programmatic-set-val">set value</button>
_x000D_
_x000D_
_x000D_


HTML

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

JS

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

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


For multiple values something like this:

$("#HouseIds").select2("val", @Newtonsoft.Json.JsonConvert.SerializeObject(Model.HouseIds));

which will translate to something like this

$("#HouseIds").select2("val", [35293,49525]);

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:

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

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

Or with JQuery:

var $newOption = $("<option selected='selected'></option>").val("TheID").text("The text")
 
$("#myMultipleSelect2").append($newOption).trigger('change');

other example

$("#myMultipleSelect2").val(5).trigger('change');

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.

$("#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


In Select2 V.4

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

I think it should work


I think you need the initSelection function

$("#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; }
});

Html:

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

JavaScript:

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

jsfiddle


To build ontop of @tomloprod's answer. By the odd chance that you are using x-editable, and have a select2(v4) field and have multiple items you need to pre-select. You can use the following piece of code:

$("#select2field").on("shown", function(e, editable){
    $(["test1", "test2", "test3", "test4"]).each(function(k, v){
        // Create a DOM Option and pre-select by default~
        var newOption = new Option(v.text, v.id, true, true);
        // Append it to the select
        $(editable.input.$input).append(newOption).trigger('change');
     });
});

and here it is in action:

_x000D_
_x000D_
var data = [_x000D_
{_x000D_
    id: 0,_x000D_
    text: 'enhancement'_x000D_
},_x000D_
{_x000D_
    id: 1,_x000D_
    text: 'bug'_x000D_
},_x000D_
{_x000D_
    id: 2,_x000D_
    text: 'duplicate'_x000D_
},_x000D_
{_x000D_
    id: 3,_x000D_
    text: 'invalid'_x000D_
},_x000D_
{_x000D_
    id: 4,_x000D_
    text: 'wontfix'_x000D_
}_x000D_
];_x000D_
_x000D_
$("#select2field").editable({_x000D_
        type: "select2",_x000D_
        url: './',_x000D_
        name: 'select2field',_x000D_
        savenochange: true,_x000D_
        send: 'always',_x000D_
        mode: 'inline',_x000D_
        source: data,_x000D_
        value: "bug, wontfix",_x000D_
        tpl: '<select style="width: 201px;">',_x000D_
        select2: {_x000D_
            width: '201px',_x000D_
            tags: true,_x000D_
            tokenSeparators: [',', ' '],_x000D_
            multiple: true,_x000D_
            data:data_x000D_
        },_x000D_
        success: function(response, newValue) {_x000D_
            console.log("success")_x000D_
        },_x000D_
        error: function(response, newValue) {_x000D_
            if (response.status === 500) {_x000D_
                return 'Service unavailable. Please try later.';_x000D_
            } else {_x000D_
                return response.responseJSON;_x000D_
            }_x000D_
        }_x000D_
    });_x000D_
_x000D_
var preselect= [_x000D_
    {_x000D_
        id: 1,_x000D_
        text: 'bug'_x000D_
    },_x000D_
    {_x000D_
    id: 4,_x000D_
    text: 'wontfix'_x000D_
}_x000D_
];_x000D_
_x000D_
 $("#select2field").on("shown", function(e, editable){_x000D_
    $(preselect).each(function(k, v){_x000D_
        // Create a DOM Option and pre-select by default~_x000D_
        var newOption = new Option(v.text, v.id, true, true);_x000D_
        // Append it to the select_x000D_
        $(editable.input.$input).append(newOption).trigger('change');_x000D_
     });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />_x000D_
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>_x000D_
_x000D_
<a id="select2field">bug, wontfix</a>
_x000D_
_x000D_
_x000D_

I guess that this would work even if you aren't using x-editable. I hope that htis could help someone.


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.

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

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
});

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

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

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.

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!


You can use this code:

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

Put your desired value instead of Your_value

Hope It will work :)


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


I did like this-

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

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();

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.


This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):

During my form/model load :

  $.ajax({
        type: "POST",
        ...        
        success: function (data) {
          selectCountries(fixedEncodeURI(data.countries));
         }

Call to select data for Select2:

var countrySelect = $('.select_country');
function selectCountries(countries)
    {
        if (countries) {
            $.ajax({
                type: 'GET',
                url: "/regions/getCountries/",
                data: $.param({ 'idsSelected': countries }, true),

            }).then(function (data) {
                // create the option and append to Select2                     
                $.each(data, function (index, value) {
                    var option = new Option(value.text, value.id, true, true);
                    countrySelect.append(option).trigger('change');
                    console.log(option);
                });
                // manually trigger the `select2:select` event
                countrySelect.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    }

and if you may be having issues with encoding you may change as your requirement:

function fixedEncodeURI(str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");

    }

if you are getting your values from ajax, before calling

_x000D_
_x000D_
$("#select_location_id").val(value);_x000D_
$("#select_location_id").select2().trigger('change');
_x000D_
_x000D_
_x000D_

confirm that the ajax call has completed, using the jquery function when

_x000D_
_x000D_
$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){_x000D_
      // the code here will be executed when all four ajax requests resolve._x000D_
      // a1, a2, a3 and a4 are lists of length 3 containing the response text,_x000D_
      // status, and jqXHR object for each of the four ajax calls respectively._x000D_
    }); 
_x000D_
_x000D_
_x000D_ as described here [Wait until all jQuery Ajax requests are done?


you can use this code :

$("#programid").val(["number:2", "number:3"]).trigger("change");

where 2 in "number:2" and 3 in "number:3" are id field in object array


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?