75

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

Leith
  • 3,139
  • 1
  • 27
  • 38
user857276
  • 1,407
  • 1
  • 14
  • 19
  • For those using the `config.data` data source (rather than outputting everything as 'options'), [this answer below](https://stackoverflow.com/a/44812660/870729) is the one that works :) – random_user_name Sep 08 '18 at 17:55

14 Answers14

66

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :

Markup

<select class="select2">
   <option id="foo">Some Text</option>
   <option id="bar" selected="selected">Other Text</option>
</select>

JavaScript

$('select').select2(); //oh yes just this!

See fiddle : http://jsfiddle.net/6hZFU/

Edit: (Thanks, Jay Haase!)

If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:

$('select').select2("val", null); //a lil' bit more :)

After this, it is simple enough to set val to "Whatever You Want".

krishwader
  • 11,341
  • 1
  • 34
  • 51
38

The above solutions did not work for me, but this code from Select2's own website did:

$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed

Webpage found here

Hope this helps for anyone who is struggling, like I was.

Curtis Weeks
  • 325
  • 2
  • 11
avebone
  • 481
  • 4
  • 4
  • 6
    For future visitors, you can combine this into a single command: `$('select').val('US').trigger('change');`, or even shorter would be `$('select').val('US').change();` – random_user_name Sep 08 '18 at 17:52
24
$("#id").select2("val", null); //this will not work..you can try

You should actually do this...intialise and then set the value..well this is also the way it worked for me.

$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
rajesh_kw
  • 1,572
  • 16
  • 14
22

One way to accomplish this is...

$('select').select2().select2('val', $('.select2 option:eq(1)').val());

So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".

<select class=".select2">
  <option id="foo">Some Text</option>
  <option id="bar">Other Text</option>
</select>

Hope this is useful to someone else.

krishwader
  • 11,341
  • 1
  • 34
  • 51
user857276
  • 1,407
  • 1
  • 14
  • 19
13

For 4.x version

$('#select2Id').val(__INDEX__).trigger('change');

to select value with INDEX

$('#select2Id').val('').trigger('change');

to select nothing (show placeholder if it is)

Wishmaster
  • 1,102
  • 14
  • 20
7

Came from the future? Looking for the ajax source default value ?

// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control
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
        }
    });
});

You're welcome.

Reference: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

Brain90
  • 1,551
  • 18
  • 21
  • This will append a new option, I believe he wants to load options and select one of those. – Marcelo Agimóvel Sep 25 '19 at 14:28
  • This is an issue with `Select2`, Yes the plugin is fine but Why Does Someone need to create a new API to preselect data. there has or should be a way to trigger the ajax query to get the dropdown and preselect a given value. – Bosco Jan 20 '20 at 10:59
5

Step 1: You need to append one blank option with a blank value in your select tag.

Step 2: Add data-placeholder attribute in select tag with a placeholder value

HTML

<select class="select2" data-placeholder='--Select--'>
  <option value=''>--Select--</option>
  <option value='1'>Option 1</option>
  <option value='2'>Option 2</option>
  <option value='3'>Option 3</option>
</select>

jQuery

$('.select2').select2({
    placeholder: $(this).data('placeholder')
});

OR

$('.select2').select2({
    placeholder: 'Custom placeholder text'
});
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26
2

e.g.

var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');

you can see it here https://select2.org/programmatic-control/add-select-clear-items

zteezy
  • 41
  • 6
1

It's easy. For example I want to select option with value 2 in default:

HTML:

<select class="select2" id="selectBox">
   <option value="1">Some Text</option>
   <option value="2">Other Text</option>
</select>

Javascript:

$("#selectBox").val('2').trigger('change')
0

Don't know others issue, Only this code worked for me.

$('select').val('').select2();
Fahad Bhuyian
  • 300
  • 2
  • 10
0

Normally we usually use active but in select2, changes to selected="selected"

Example using Python/Flask

HTML:

<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
  {% for x in list%}
  <option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
  {% endfor %}
</select>

JQuery:

$(document).ready(function() {
        $('.js-example-basic-multiple').select2();
    });

    $(".js-example-theme-multiple").select2({
        theme: "classic",
        placeholder: 'Select your option...'
    });
-1
    $('select').select2("val",null);
charu joshi
  • 113
  • 12
  • 3
    Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Brian Tompsett - 汤莱恩 Jun 21 '16 at 16:17
-1

If you are using an array data source you can do something like below -

$(".select").select2({
    data: data_names
});
data_names.forEach(function(name) {
    if (name.selected) {
        $(".select").select2('val', name.id);
    }
});

This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
-2

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          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
Ajeet Lakhani
  • 3,768
  • 2
  • 22
  • 37