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

16

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?

Postaxial answered 28/10, 2013 at 16:20 Comment(0)
S
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');
Samella answered 27/5, 2015 at 8:33 Comment(12)
This is the right answer: it works in both mono-select and multi-selectBeating
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().Underlaid
If this doesn't work correctly add a setTimeout: setTimeout(function(){ $("select").val("1").trigger("change"); }, 1000);Hammered
@Underlaid 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)Laicize
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();Laicize
your update statement $("select").val("1").trigger("change"); help solve my problem, thank youAdna
See my answer below for an example of how to solve @Underlaid problemGetup
What if you need to select more than one element?Wiersma
@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 $.eachSamella
So there is no way how to select by index, only by the actual value? Seriously guys, this is not good engineering...Hansom
@Hansom I do not follow your question. Do you mean selecting the option by an index rather than a value?Samella
I have updated the solution with @Getup solution to firing just select2 change event. This solves van_folmert and onebree issues. Thanks :)Samella
A
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.

Aldosterone answered 28/10, 2013 at 16:25 Comment(8)
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.Postaxial
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.Aldosterone
@AdamKDean: One can test additionally whether <select> where converted to select2 control by testing existense of the class select2-offscreen on the <select>. 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.Tally
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.Postaxial
@AdamKDean, Could you please paste your solution here. I think, I am also in the same situation.Furr
I no longer have it I'm afraid, I ended up abandoning that particular component. Really sorry man!Postaxial
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));Acclimatize
Now deprecated: github.com/select2/select2/blob/master/dist/js/…Dichromatic
S
32
this.$("#yourSelector").select2("data", { id: 1, text: "Some Text" });

this should be of help.

Swipe answered 8/7, 2014 at 7:5 Comment(1)
Multiple values example: this.$("#yourSelector").select2("data", [{ id: 1, text: "Some Text" },{ id: 2, text: "Some Other Text" }]);Uncrowned
C
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

Cowie answered 12/8, 2014 at 10:1 Comment(0)
J
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");
    
Jeaniejeanine answered 12/1, 2016 at 2:19 Comment(3)
I find this cleaner than messing with the select2 'data' :) Change the dom, let select2 figure the rest out.Capri
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. :)Erotomania
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!!!!Driven
K
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");
Kortneykoruna answered 18/6, 2014 at 18:54 Comment(0)
G
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');
Getup answered 10/11, 2016 at 11:31 Comment(2)
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.Heterozygous
this '$(element).val(val).trigger('change.select2');' worked for me. Thank you @minlare.Sheldon
I
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.

Ioved answered 5/8, 2016 at 15:50 Comment(0)
L
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()

Laresa answered 16/12, 2015 at 7:9 Comment(1)
this will not work if you enter string under square brackets.Laresa
M
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

Mazurek answered 27/7, 2017 at 19:6 Comment(1)
Try to trigger('change.select2').trigger('select2:select'); if just change is not enoughRodriquez
E
5

do this

 $('select#id').val(selectYear).select2();
Evergreen answered 21/3, 2018 at 11:15 Comment(2)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Horselaugh
I do not have knowledge about JqGrid but with this code you can change select2 value in simple wayEvergreen
G
4

My Expected code :

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

working perfectly thank to @PanPipes for the usefull one.

Grannia answered 23/6, 2015 at 7:8 Comment(0)
R
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
        }
    });
});
Ruvolo answered 13/9, 2017 at 4:4 Comment(0)
E
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'); 
Especially answered 15/1, 2019 at 5:2 Comment(0)
B
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
Benny answered 20/6, 2019 at 3:48 Comment(0)
L
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

Leveille answered 22/3, 2018 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.