Programmatically set the value of a Select2 ajax

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.


Note: For multi select, execute the above code for each item, like this :

  // for each initially selected ids, execute the above code to add the id to the selection.
  [{id: 5, text: 'op5'}, {id: 10, text: 'op10'}].forEach(option => {
    $("#selectelement").select2("trigger", "select", {data: { id: option.id, text: option.text }});
  })

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)