Programmatically set the value of a Select2 ajax

caponica picture caponica · Aug 20, 2014 · Viewed 86.7k times · Source

I have a Select2 auto-complete input (built via SonataAdmin), but cannot for the life of me figure out how to programmatically set it to a known key/value pair.

There's a JS Fiddle here that shows roughly what I have. What I want to know is what function I can attach to the button so that

  • the Select2 field shows the text "NEW VALUE" to the user, and
  • the Select2 field will submit a value of "1" when the form is sent to the server

I have tried all sorts of combinations of jQuery and Select2 data and val methods, called against various inputs on the page, but nothing seems to work... surely there's some way to do this?

-- Edit --

The accepted answer below is very useful, helps shed some light on the right way to initialise the selection and explains what initSelection is for.

Having said that, it seems that my biggest mistake here was the way I was trying to trigger the change.

I was using:

$(element).select2('data', newObject).trigger('change');

But this results in an empty add object inside select2's change event.

If, instead, you use:

$(element).select2('data', newObject, true);

then the code works as it should, with the newObject available in select2's change event and the values being set correctly.

I hope this extra information helps somebody else!

Answer

Mark picture Mark · Jul 19, 2016

Note this was tested with version 4+

I was finally able to make progress after finding this discussion: https://groups.google.com/forum/#!topic/select2/TOh3T0yqYr4

The last comment notes a method that I was able to use successfully.

Example:

$("#selectelement").select2("trigger", "select", {
    data: { id: "5" }
});

This seems to be enough information for it to match the ajax data, and set the value correctly. This helped immensely with Custom Data Adapters.