JQuery select2 set default value from an option in list?

JavascriptJqueryHtml SelectJquery Select2

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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)

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

$('select').val('').select2();

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

	$('select').select2("val",null);

Solution 13 - Javascript

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.

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser857276View Question on Stackoverflow
Solution 1 - JavascriptkrishwaderView Answer on Stackoverflow
Solution 2 - JavascriptaveboneView Answer on Stackoverflow
Solution 3 - Javascriptrajesh_kwView Answer on Stackoverflow
Solution 4 - Javascriptuser857276View Answer on Stackoverflow
Solution 5 - JavascriptWishmasterView Answer on Stackoverflow
Solution 6 - JavascriptBrain90View Answer on Stackoverflow
Solution 7 - JavascriptSoubhagya Kumar BarikView Answer on Stackoverflow
Solution 8 - JavascriptzteezyView Answer on Stackoverflow
Solution 9 - JavascriptFahad BhuyianView Answer on Stackoverflow
Solution 10 - JavascriptAndres RaveView Answer on Stackoverflow
Solution 11 - JavascriptSaeed.ModarresiView Answer on Stackoverflow
Solution 12 - Javascriptcharu joshiView Answer on Stackoverflow
Solution 13 - JavascriptAniket ThakurView Answer on Stackoverflow
Solution 14 - JavascriptAjeet LakhaniView Answer on Stackoverflow