186

I'm using Oleg's select2 demo, but I am wondering whether it would be possible to change the currently selected value in the dropdown menu.

For example, if the four values loaded were: "Any", "Fruit", "Vegetable", "Meat" and the dropdown list defaulted to "Any", how would I be able to change that to "Fruit" in the JqGrid event loadComplete?

Is this possible?

Adam K Dean
  • 7,387
  • 10
  • 47
  • 68

16 Answers16

420

For select2 version >= 4.0.0

The other solutions might not work, however the following examples should work.

Solution 1: Causes all attached change events to trigger, including select2

$('select').val('1').trigger('change');

Solution 2: Causes JUST select2 change event to trigger

$('select').val('1').trigger('change.select2');

See this jsfiddle for examples of these. Thanks to @minlare for Solution 2.

Explanation:

Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:

$('#my-best-friend').select2();

Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:

$('#my-best-friend').val('').trigger('change');

Or say I make the system select the next in the list instead of Bob:

// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');  

Notes on Select 2 website (see Deprecated and removed methods) that might be useful for others:

.select2('val') The "val" method has been deprecated and will be removed in Select2 4.1. The deprecated method no longer includes the triggerChange parameter.

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');
Community
  • 1
  • 1
PanPipes
  • 4,584
  • 1
  • 17
  • 24
  • 8
    This is the right answer: it works in both mono-select and multi-select – Giovanni Di Milia Jul 29 '15 at 18:48
  • 4
    This is an acceptable solution only if one doesn't have any custom actions binded to the `change` event (like reloading the form). Otherwise those actions would be called redundantly upon triggered `change()`. – van_folmert Feb 22 '16 at 10:37
  • If this doesn't work correctly add a setTimeout: setTimeout(function(){ $("select").val("1").trigger("change"); }, 1000); – Abel Apr 25 '16 at 21:23
  • @van_folmert I have that same issue. Ideally, I want to change what is shown as selected, without firing off an event (since I have a custom one bound to `onChange`) – onebree Jul 28 '16 at 15:48
  • Okay, I just figured out a workaround. Instead of changing the value after select2 is initialized for that element, do it before. It will _not_ fire off the change event: `$("select").val("1").select2();` – onebree Jul 28 '16 at 15:53
  • your update statement $("select").val("1").trigger("change"); help solve my problem, thank you – widjajayd Oct 10 '16 at 15:50
  • 1
    See my answer below for an example of how to solve @van_folmert problem – minlare Nov 10 '16 at 11:33
  • What if you need to select more than one element? – Brane Nov 20 '16 at 01:11
  • @raBne Are you setting them all to the same value? If not, you will have to do one jQuery select after another. If you are, just widen the jQuery select to find all elements then use [$.each](http://api.jquery.com/jquery.each/) – PanPipes Nov 21 '16 at 14:31
  • So there is no way how to select by index, only by the actual value? Seriously guys, this is not good engineering... – Natix Mar 12 '17 at 01:36
  • @Natix I do not follow your question. Do you mean selecting the option by an index rather than a value? – PanPipes Mar 12 '17 at 09:10
  • I have updated the solution with @minlare solution to firing just select2 change event. This solves van_folmert and onebree issues. Thanks :) – PanPipes Mar 13 '17 at 10:53
138

Looking at the select2 docs you use the below to get/set the value.

$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value

@PanPipes has pointed out that this has changed for 4.x (go toss him an upvote below). val is now called directly

$("#select").val("CA");

So within the loadComplete of the jqGrid you can get whatever value you are looking for then set the selectbox value.

Notice from the docs

Notice that in order to use this method you must define the initSelection function in the options so Select2 knows how to transform the id of the object you pass in val() to the full object it needs to render selection. If you are attaching to a select element this function is already provided for you.

Jack
  • 8,851
  • 3
  • 21
  • 26
  • Doesn't appear to work with the demo I'm looking at. Not sure why, it may be something to do with the way it plugs into JqGrid. – Adam K Dean Oct 28 '13 at 16:44
  • 1
    Updated the answer. Looks like you'll manually have to add that function to the select2 initialization so it knows how to handle the `val` call. – Jack Oct 28 '13 at 16:53
  • 1
    @AdamKDean: One can test additionally whether ``. All elements of searching toolbar have id which start with `gs_` prefix and have the name like in `colModel`. You can use `getGridParam` to get `colModel`. – Oleg Oct 28 '13 at 17:16
  • Thanks, I've managed to get the filter information, I just need a way to set it after the filter bar is recreated with the `select2` select. I'll take another look today, maybe with fresh eyes I can fix it. Thanks again. Update: wrapping the code in a boolean check fixed the issue I was having, though it stopped refreshing of the search bar rather than selecting the previous element again. – Adam K Dean Oct 29 '13 at 08:36
  • @AdamKDean, Could you please paste your solution here. I think, I am also in the same situation. – Jaikrat Feb 28 '14 at 09:36
  • I no longer have it I'm afraid, I ended up abandoning that particular component. Really sorry man! – Adam K Dean Feb 28 '14 at 10:43
  • I was in trouble to set the value in version 3.5.3 and after hours racking my brain, I found that the plugin doesn't accept string value when you have the id setted before. So for me the solution was to set the value with parseInt. `$("#select").select2("val", parseInt(myId));` – Aline Matos Apr 18 '16 at 14:17
  • 1
    Now deprecated: https://github.com/select2/select2/blob/master/dist/js/select2.full.js#L5560 – Andrey Jul 24 '16 at 21:05
32
this.$("#yourSelector").select2("data", { id: 1, text: "Some Text" });

this should be of help.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • 4
    Multiple values example: this.$("#yourSelector").select2("data", [{ id: 1, text: "Some Text" },{ id: 2, text: "Some Other Text" }]); – RodneyRd Jul 22 '14 at 07:54
18

This should be even easier.

$("#e1").select2("val", ["View" ,"Modify"]);

But make sure the values which you pass are already present in the HTMl

Mo.
  • 26,306
  • 36
  • 159
  • 225
Neelu
  • 251
  • 3
  • 6
18

If you want to add new value='newValue' and text='newLabel', you should add this code:

  1. Add new Option to <select>:

    var opt = "<option value='newValue' selected ='selected'>" + newLabel+ " </option>";
    $(selLocationID).html(opt);
    
  2. Trigger <select> change to selected value:

    $(selLocationID).val('newValue').trigger("change");
    
VLS
  • 2,306
  • 4
  • 22
  • 17
Trong
  • 181
  • 1
  • 2
  • I find this cleaner than messing with the select2 'data' :) Change the dom, let select2 figure the rest out. – Paulj Jan 25 '16 at 21:53
  • I'm testing on Safari, and this is the only solution that actually works. The others are more eloquent and I would prefer them, but more than anything, I prefer working code. And this is that. :) – David Mar 04 '16 at 05:56
  • Thanks a million for this! I am working with select 2 boxes where both boxes are populated with Ajax and I used extra data properties for the first box to set the value of the second using this. Again thank you!!!! – Someone Oct 26 '16 at 11:06
16

Just wanted to add a second answer. If you have already rendered the select as a select2, you will need to have that reflected in your selector as follows:

$("#s2id_originalSelectId").select2("val", "value to select");
Abram
  • 39,950
  • 26
  • 134
  • 184
12

You have two options - as @PanPipes answer states you can do the following.

$(element).val(val).trigger('change');

This is an acceptable solution only if one doesn't have any custom actions binded to the change event. The solution I use in this situation is to trigger a select2 specific event which updates the select2 displayed selection.

$(element).val(val).trigger('change.select2');
minlare
  • 2,454
  • 25
  • 46
  • Yes, this is the best all-around solution. Really, I think Select2 should trigger the internal 'change.select2' event automatically to update the display when the value is changed. But, this at least provides a simple way to update the display to match the new value, without triggering custom change event handlers. – DaveInMaine Feb 04 '17 at 06:51
  • this '$(element).val(val).trigger('change.select2');' worked for me. Thank you @minlare. – Ray Nov 27 '17 at 13:34
9

Having some troubles with setting a String option selected in a select2:

With the option: "option string1 /option" used:

$('#select').val("string1").change(); 

BUT with an option with a value: option value "E" string1 /option :

$('#select').val("E").change(); // you must enter the Value instead of the string

Hopes this help someone struggling with the same issue.

Michael Parker
  • 12,724
  • 5
  • 37
  • 58
Aldodzb
  • 106
  • 1
  • 3
5

if you want to select a single value then use $('#select').val(1).change()

if you want to select multiple values then set value in array so you can use this code $('#select').val([1,2,3]).change()

Utkarsh Pandey
  • 1,682
  • 1
  • 12
  • 11
5

For V4 Select2 if you want to change both the value of the select2 and the text representation of the drop down.

var intValueOfFruit = 1;
var selectOption = new Option("Fruit", intValueOfFruit, true, true);
$('#select').append(selectOption).trigger('change');

This will set not only the value behind the scenes but also the text display for the select2.

Pulled from https://select2.github.io/announcements-4.0.html#removed-methods

Rmalmoe
  • 993
  • 11
  • 13
  • Try to trigger('change.select2').trigger('select2:select'); if just change is not enough – Tebe Apr 19 '18 at 07:57
5

do this

 $('select#id').val(selectYear).select2();
Jaskaran singh Rajal
  • 2,270
  • 2
  • 17
  • 29
4

My Expected code :

$('#my-select').val('').change();

working perfectly thank to @PanPipes for the usefull one.

2

if you have ajax data source please refer this for bugs free

https://select2.org/programmatic-control/add-select-clear-items

// 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
        }
    });
});
1

if you want to set a selected item when you know the text from drop down list and don't know the value, here is an example:

Say you figured out a timezone and want to set it, but values has time_zone_id in them.

        var timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
        var $select2 = $('#time-zone');
        var selected = $select2.find("option:contains('"+timeZone+"')").val();
        $select2.val(selected).trigger('change.select2'); 
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
1

you can simply use the get/set method for set the value

$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value

or you can do this:

$('#select').val("E").change(); // you must enter the Value instead of the string
Foram
  • 483
  • 5
  • 12
0
// 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
        }
    });
});

Font : Select 2 documentation

CodeNoob
  • 345
  • 4
  • 17