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?
this should be of help.
do this
Font : Select 2 documentation
Looking at the select2 docs you use the below to get/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
For V4 Select2 if you want to change both the value of the select2 and the text representation of the drop down.
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
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
Solution 2: Causes JUST select2 change event to trigger
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:
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:
Or say I make the system select the next in the list instead of Bob:
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.