How to set selected value of jQuery Select2?

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

Leave a Comment