Select2 Ajax Change Value

Describes the issue filed on Select2: https://github.com/select2/select2/issues/4034

by Kushal Jayswal

HTML

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>
<select id="user-email-address" name="email" style='width: 200px'></select>
<button id="set-email-manually">
  Set Manually
</button>
<p>Changing the field to <code>[email protected]</code> or any of the preloaded values works, and triggers the change event with the correct data. </p>
<p>
  Clicking the Set Manually button updates the field and triggers the change event correctly, but select2 does not reflect the change.
</p>

<div id="output">
</div>

CSS

#output {
  font: monospace;
  border: 1px solid black;
  padding: 10px;
}

JavaScript

$(document).ready(function() {
  $('#user-email-address').change(function(e) {
    $('#output').append('<p>' + $(this).val() + "</p>");
  });
  $('#user-email-address').select2({
    placeholder: "Type an email address",
    ajax: {
      url: 'https://liferay-dev.netacad.com/api/jsonws?location-list-portlet/city/get-cities-by-country-id-and-state-id-and-name',
      dataType: 'json',
      delay: 250,
      data: function(params) {
        var query = {
          countryId: 53107,
          stateId: 50251,
          cityName: params.term,
          type: 'public'
        }

        // Query parameters will be ?search=[term]&type=public
        return query;
      },
      processResults: function(data, params) {
        var payload = {
          results: data
        };
        return payload;
      },
      cache: true
    },
    templateResult: function(result) {
      return result.name;
    },
    templateSelection: function(selection) {
      return selection.name;
    },
    minimumInputLength: 3
  });
  $('#set-email-manually').click(function(e) {

    e.preventDefault();

    // THIS DOESN'T WORK PROPERLY!?

    $('#user-email-address')
      .empty()
      .append('<option selected value="[email protected]">[email protected]</option>');
    $('#user-email-address').trigger('change');

  });

});