JQuery select2 set default value from an option in list?
Asked Answered
C

14

77

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

Carree answered 6/6, 2013 at 18:39 Comment(1)
For those using the config.data data source (rather than outputting everything as 'options'), this answer below is the one that works :)Paz
M
67

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

Microcopy answered 6/6, 2013 at 19:3 Comment(2)
I could not get the above JavaScript to work for me. I did get the following to work: $("#id").select2("val", null);Nadeau
above code works fine for single value, but in case of multiple values only one value is getting selectedEchinoid
T
39

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.

Terbecki answered 28/6, 2017 at 21:15 Comment(1)
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();Paz
A
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');
Almatadema answered 6/9, 2013 at 18:56 Comment(1)
no joy here. With or without initialization, this simply does not work with AJAX data!Roots
C
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.

Carree answered 6/6, 2013 at 18:39 Comment(5)
your html markup has a class with a . in it. so basically your code wont set the value because youre selecting the wrong element.Microcopy
or rather an element which doesnt exist :)Microcopy
If you need to have the clear button after setting a selected value use: $('.select').select2({allowClear: true}).select2('val', $('.select2 option:eq(1)').val());Kerrill
$('#source_timezone').val('US/Eastern').select2()Collocate
This works great, but how do you make it select multiple options, not just the 1?Disembodied
P
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)

Primus answered 19/12, 2017 at 7:43 Comment(1)
why is it different from @Terbecki answer? I see the same answer made 5 month later.Centipede
D
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

Dogged answered 18/8, 2019 at 6:40 Comment(2)
This will append a new option, I believe he wants to load options and select one of those.Zia
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.Acquiescence
X
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'
});
Xi answered 18/12, 2020 at 8:47 Comment(0)
S
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

Spondaic answered 25/9, 2021 at 4:28 Comment(1)
how to handle multiple attributes not just id and a text but also a custom attribute ?Wace
M
1

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

$('select').val('').select2();
Millimicron answered 24/12, 2018 at 9:22 Comment(1)
because you did not try .trigger('change');Centipede
B
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')
Bhang answered 12/1, 2022 at 6:26 Comment(0)
E
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...'
    });
Exult answered 11/9, 2021 at 3:3 Comment(0)
C
-1
    $('select').select2("val",null);
Chlamydeous answered 21/6, 2016 at 10:45 Comment(1)
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.Schug
O
-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.

Omnipotence answered 10/12, 2017 at 16:26 Comment(0)
C
-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
Catabolism answered 15/1, 2016 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.