How do I change selected value of select2 dropdown with JqGrid?

JqueryJqgridUi Select2

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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.

Solution 3 - Jquery

this.$("#yourSelector").select2("data", { id: 1, text: "Some Text" });

this should be of help.

Solution 4 - Jquery

This should be even easier.

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

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

Solution 5 - Jquery

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

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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.

Solution 9 - Jquery

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

Solution 10 - Jquery

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

Solution 11 - Jquery

do this

 $('select#id').val(selectYear).select2();

Solution 12 - Jquery

My Expected code :

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

working perfectly thank to @PanPipes for the usefull one.

Solution 13 - Jquery

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

Solution 14 - Jquery

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

Solution 15 - Jquery

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

Solution 16 - Jquery

// 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

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
QuestionAdam K DeanView Question on Stackoverflow
Solution 1 - JqueryPanPipesView Answer on Stackoverflow
Solution 2 - JqueryJackView Answer on Stackoverflow
Solution 3 - JqueryYasser ShaikhView Answer on Stackoverflow
Solution 4 - JqueryNeeluView Answer on Stackoverflow
Solution 5 - JqueryTrongView Answer on Stackoverflow
Solution 6 - JqueryAbramView Answer on Stackoverflow
Solution 7 - JqueryminlareView Answer on Stackoverflow
Solution 8 - JqueryAldodzbView Answer on Stackoverflow
Solution 9 - JqueryUtkarsh PandeyView Answer on Stackoverflow
Solution 10 - JqueryRmalmoeView Answer on Stackoverflow
Solution 11 - JqueryJaskaran singh RajalView Answer on Stackoverflow
Solution 12 - JqueryAbdullah Sheik DavoodView Answer on Stackoverflow
Solution 13 - JqueryHarshan MorawakaView Answer on Stackoverflow
Solution 14 - JqueryYevgeniy AfanasyevView Answer on Stackoverflow
Solution 15 - JqueryForamView Answer on Stackoverflow
Solution 16 - JqueryCodeNoobView Answer on Stackoverflow