How to set selected value of jQuery Select2?
Asked Answered
E

36

158

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.

Enteron answered 7/8, 2014 at 16:45 Comment(5)
You should be able to just set the selected value in the html or use $("#programid").val()Jehiel
@ExplosionPills Negative, I tried that too I got a blank value. How should I use programid.val()? I got the value from the server then I need to set it into this hidden field of select2.Enteron
@Enteron Not sure if I get what you mean. Are you trying to set the "selected" value of the Select2 component to one of the AJAX-retrieved results?Karlene
@AnPhan Yes, is there a way to do that?Enteron
@Enteron There is. Check my answer below.Karlene
K
90

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

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

Where the second parameter is an object with expected values.

UPDATE:

This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

Example:

$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});

Thanks to @NoobishPro

Karlene answered 9/8, 2014 at 9:53 Comment(9)
I was trying with the id only select2('val', '1') but it wasn't work.. ThanksEnteron
This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}Homan
same here on v4. Been pulling my hair out on this one. I don't think it's possible without going to JavaScript solutions. Looking for another jQuery/Bootstrap Select2 dropdown now (2 days of fiddling every conceivable method - no joy!)Avens
Select2 v4: $('#inputID').val(100).trigger('change') See select2.github.io/…Petrol
@Homan & An Phan - Thanks for the Answer & CommentFelisafelise
@HamedH I wouldn't expect it to since the selected value has to be present for it to be selected.Petrol
V4 docs to use select2.org/programmatic-control/add-select-clear-itemsGoodnatured
Additional for the answer - for multi-values need use $('#all_contacts').select2('data', [{id: '123', text: 'res_data.primary_email'},{id: '124', text: 'res_data.secondary_email'}]);Paederast
I also have the same problem then i have added extra parameter selected true, Now its working. $('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email', 'selected' : true});Berryman
T
215

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');
Tempe answered 15/1, 2015 at 13:43 Comment(6)
trigger('change'); is the important partBunyip
$("#mySelect2").select2("val", "0") - this will trigger jquery event of value changes. How to prevent this from happening. Usually when user submit form, after done, I reset all form data. Reset will not reset select2. Using select2("val", "0") will trigger changes which is crazy as no action from user.Bedlamite
Version 4 select2.org/programmatic-control/add-select-clear-itemsGoodnatured
Commended for the .trigger('change')Vivi
I cannot stress enough the trigger('change') part. The thing won't even update its own visual appearance (i.e. display the selected option) without it.Maje
trigger('change'); is also needed in <v4.Palmapalmaceous
K
90

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

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

Where the second parameter is an object with expected values.

UPDATE:

This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

Example:

$('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});

Thanks to @NoobishPro

Karlene answered 9/8, 2014 at 9:53 Comment(9)
I was trying with the id only select2('val', '1') but it wasn't work.. ThanksEnteron
This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}Homan
same here on v4. Been pulling my hair out on this one. I don't think it's possible without going to JavaScript solutions. Looking for another jQuery/Bootstrap Select2 dropdown now (2 days of fiddling every conceivable method - no joy!)Avens
Select2 v4: $('#inputID').val(100).trigger('change') See select2.github.io/…Petrol
@Homan & An Phan - Thanks for the Answer & CommentFelisafelise
@HamedH I wouldn't expect it to since the selected value has to be present for it to be selected.Petrol
V4 docs to use select2.org/programmatic-control/add-select-clear-itemsGoodnatured
Additional for the answer - for multi-values need use $('#all_contacts').select2('data', [{id: '123', text: 'res_data.primary_email'},{id: '124', text: 'res_data.secondary_email'}]);Paederast
I also have the same problem then i have added extra parameter selected true, Now its working. $('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email', 'selected' : true});Berryman
C
30

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

Clementina answered 22/12, 2014 at 3:30 Comment(4)
how to set by text rather than valPraetorian
The question was how to do this after loading with AJAX call. This answer does not work in this case.Avens
this will trigger select2 value changes which will be weird if you have this event to process, and it triggered without the user doing itBedlamite
Add .trigger("change") at the endThymelaeaceous
E
30

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.

$("#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>
Eddings answered 22/2, 2016 at 1:3 Comment(3)
I'm using different displayKey and stuff (was bad idea though) - this helps out for my acceptance tests with Codeception perfectlySimpleminded
Tedious, for sure, but, like everyone is finding out Select2 v4 simply has no way of doing something so ridiculously simple as setting a default selectionAvens
I found this answer to be the the only way to make select2 v4 - ajax select.Sweyn
W
26

I did like this-

$("#drpServices").select2().val("0").trigger("change");
Whitebook answered 26/5, 2018 at 6:4 Comment(3)
Please provide some explanation to help users understand how your code work and to answer the OP's question.Cottle
@Ivan, I was doing like this $("#drpServices").val("0"); which will not select the taxt in select2 dropdown, for affecting both value and text we need trigger change function of select2. This is working perfectly for me. I hope users will understand.Whitebook
This was the best answer in my opinion. It is easy and can be added to a straight JS Ajax call after response is received. Thanks.Formidable
C
14
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.

Cocci answered 7/11, 2016 at 0:20 Comment(3)
var $option = $("<option selected></option>").val('1').text("Pick me"); $('#select_id').append($option).trigger('change');Cocci
thanks. confirmed works on version 4.0.0 (ajax call)Raggedy
If you are using a searchable box with ajax, this is the right solution. This one worked for me June 2019.Sentient
L
11

Set the value and trigger the change event immediately.

$('#selectteam').val([183,182]).trigger('change');
Lennox answered 27/8, 2019 at 15:12 Comment(2)
Thanks you same my dayMagical
the fact that you can pass an array of ids to .val() is useful if you want to set more than one value as selectedAblate
C
10

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

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>
Clathrate answered 1/2, 2016 at 13:30 Comment(10)
How can I set the value without triggering the change event? The change event triggers my own event handlers that are meant for when user changes the value manually.Combust
The other option is to destroy and re-call the plugin again.. See the updated code..Clathrate
Is there a way to get the options I've originally passed to select2 so that I wouldn't have to duplicate them? Anyway this solution seems more like a hack.Combust
Sure it's hach. The official way according the docs is to trigger change event. so that I wouldn't have to duplicate them Why do have to duplicate them? When you do destroy the select is still there with all his options.Clathrate
I meant the options passed to select2: $example.select2({ ... this ... })Combust
Store it into a variable like: var opt = {...this...}; $example.select2(opt)` or create a function which return the options.Clathrate
Yeah, that's exactly what I'd like to avoid because select2 initialization and the place where I just need to set a value are in entirely different contexts.Combust
Another way is to store the options before the destroy using $(".js-example-placeholder-single").data('select2').options.options (It's return the all of them but I think that it will OK if you will pass them all). Maybe it's not fully solution but it's a start.. i.stack.imgur.com/fGlGs.pngClathrate
This is the technique I've been using as well. Have you had any luck getting it to work with the tags: true option? I.e., setting the select to a value that doesn't appear in the dropdown?Idolla
This is the technique I've been using as well which one? setting the select to a value that doesn't appear in the dropdown Why? Are the options getting from an ajax request? Do you have fiddle or public URL so I could see the problem?Clathrate
B
10
$('#inputID').val("100").select2();

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

Bratcher answered 18/5, 2020 at 3:37 Comment(0)
D
8

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

Dualistic answered 28/11, 2016 at 7:46 Comment(0)
C
7

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; }
});
Clementina answered 14/4, 2015 at 11:2 Comment(1)
This is working. But is deprecated as of version 4.0Asper
P
6

In Select2 V.4

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

I think it should work

Pomposity answered 30/8, 2017 at 10:2 Comment(0)
F
5

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

Freightage answered 3/3, 2016 at 20:38 Comment(1)
i wish i can like this a thousand times..you saved meGlittery
O
3
    $("#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.

Obscene answered 8/11, 2019 at 8:59 Comment(0)
M
2

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();
Maxantia answered 31/10, 2016 at 13:48 Comment(1)
I get the error "Uncaught TypeError: $(...).select2(...).change is not a function(…)" when doing it this way. I don't think it's possible with version 4.x of Select2 - nothing here works with ajax.Avens
C
2

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);
Charlotte answered 17/1, 2018 at 15:36 Comment(0)
P
2

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

Pea answered 8/7, 2018 at 17:37 Comment(0)
D
2

This work for me fine:

        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);
        $('#select2_id').append(newOption).trigger('change');
        callback({"text": data.title, "id": data.id});
    });
},
Disrelish answered 14/3, 2021 at 6:30 Comment(0)
M
2

Preselecting options in an remotely-sourced (AJAX) Select2 For Select2 controls that receive their data from an AJAX source, using .val() will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching. This is further complicated by server-side filtering and pagination - there is no guarantee when a particular item will actually be loaded into the Select2 control!

The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:

$('#mySelect2').select2({
ajax: {
    url: '/api/students'
}
});
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');

// manually trigger the `select2:select` event
studentSelect.trigger({
    type: 'select2:select',
    params: {
        data: data
    }
});
});
Modulator answered 28/10, 2021 at 23:6 Comment(1)
we need another ajax request to get the other information of option such as 'text' or 'label'. currently select2 does not provide a builtin method where you can set a pre selected that only need is 'id'. yes you can set element.val(id) but this method only works in a non ajax select2 or ajax but the user need to select manually the item before val works.Petrillo
M
1

You can use this code:

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

Put your desired value instead of Your_value

Hope It will work :)

Meneau answered 28/1, 2018 at 14:28 Comment(0)
P
1

Official Select2 documentation says:

For Select2 controls that receive their data from an AJAX source, using .val() will not work. The options won't exist yet, because the AJAX request is not fired until the control is opened and/or the user begins searching.

To set value in select2 field place <option> tag inside <select> tag during page rendering:

<select id="input-degree">
    <option value="1">Art</option>
</select>

When page is loaded you'll see Art in select2 field. If we click on this field data will be fetched from the server via ajax and other options will be shown.

Publishing answered 11/8, 2021 at 13:50 Comment(0)
F
0

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
Fade answered 15/1, 2016 at 11:55 Comment(0)
M
0

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>
Marjoriemarjory answered 8/1, 2017 at 12:25 Comment(0)
T
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.

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

Tieback answered 17/7, 2017 at 19:3 Comment(0)
R
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.

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!

Ranunculaceous answered 31/1, 2018 at 11:59 Comment(0)
T
0

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]);
Terisateriyaki answered 26/9, 2018 at 14:6 Comment(0)
S
0

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,"");

    }
Stortz answered 7/9, 2019 at 14:32 Comment(0)
B
0

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:

var data = [
{
    id: 0,
    text: 'enhancement'
},
{
    id: 1,
    text: 'bug'
},
{
    id: 2,
    text: 'duplicate'
},
{
    id: 3,
    text: 'invalid'
},
{
    id: 4,
    text: 'wontfix'
}
];

$("#select2field").editable({
        type: "select2",
        url: './',
        name: 'select2field',
        savenochange: true,
        send: 'always',
        mode: 'inline',
        source: data,
        value: "bug, wontfix",
        tpl: '<select style="width: 201px;">',
        select2: {
            width: '201px',
            tags: true,
            tokenSeparators: [',', ' '],
            multiple: true,
            data:data
        },
        success: function(response, newValue) {
            console.log("success")
        },
        error: function(response, newValue) {
            if (response.status === 500) {
                return 'Service unavailable. Please try later.';
            } else {
                return response.responseJSON;
            }
        }
    });

var preselect= [
    {
        id: 1,
        text: 'bug'
    },
    {
    id: 4,
    text: 'wontfix'
}
];

 $("#select2field").on("shown", function(e, editable){
    $(preselect).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');
     });
});
<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" />

<link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>

<a id="select2field">bug, wontfix</a>

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

Bisectrix answered 16/3, 2020 at 14:30 Comment(0)
S
0

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

Suffuse answered 2/2, 2021 at 10:52 Comment(0)
U
0
[jsfiddle_link][1] <select id="lang" multiple >
       <option value="php">php</option>
        <option value="asp">asp</option>
       <option value="java">java</option>
  </select>

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- language: lang-html -->


  [1]: https://jsfiddle.net/xrug7f6k/
Uninterested answered 14/3, 2022 at 6:11 Comment(0)
L
0

Have you tried to set the option's "selected flag" to be true?

Lanna answered 13/7, 2022 at 4:51 Comment(1)
Please phrase this as an explained conditional answer, in order to avoid the impression of asking a clarification question instead of answering (for which a comment should be used instead of an answer, compare meta.stackexchange.com/questions/214173/… ). For example like "If your problem is ... then the solution is to .... because .... ."Phagy
P
0

we need another ajax request to get the other information of option such as 'text' or 'label'. currently select2 does not provide a built in method where you can set a pre selected that only need is 'id'. yes you can set element.val(id) but this method only works in a non ajax select2 or ajax but the user need to select manually the item before val works.

async sel2_set_value(ref_instance, id_key, id_value, text_key) {

        const $element = this.getElementByRef(ref_instance);
        const select2Instance = $element.data('select2');
        const options = select2Instance.options.options;

        const where_statement = {};
        where_statement[id_key] = id_value;

        const response = await jQuery.ajax({
            "url"  : options.url,
            "data" : { "where" : JSON.stringify(where_statement)}
        });

        if(response.data.length <= 0) {
            return;
        }

        const text = response.data[0].attributes[text_key];

        const option = new Option(text, id_value, true, true);
        $element.append(option).trigger('change');


    }
Petrillo answered 18/3 at 17:59 Comment(0)
G
-1

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
});
Glyceryl answered 21/6, 2016 at 10:8 Comment(0)
S
-1

if you are getting your values from ajax, before calling

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

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

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
      // the code here will be executed when all four ajax requests resolve.
      // a1, a2, a3 and a4 are lists of length 3 containing the response text,
      // status, and jqXHR object for each of the four ajax calls respectively.
    }); 
as described here [Wait until all jQuery Ajax requests are done?
Stancil answered 17/1, 2020 at 10:18 Comment(0)
D
-1

After getting a response to your request, you can update the select2 value this way:

let response = JSON.parse(your_response);
let key_to_select = response.your_key;

$(document).find('yourIdorClass').val(key_to_select ).trigger("change");
Dilatometer answered 13/6, 2023 at 11:39 Comment(0)
Q
-4

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.

Quizmaster answered 19/4, 2018 at 23:26 Comment(2)
This answer is an awful hack which wouldn't even set the value correctly.Ranunculaceous
I'm sorry about that. I'll edit my answer to explain why I've posted it.Quizmaster

© 2022 - 2024 — McMap. All rights reserved.