title: Select value of jQuery select2 not updating correctly
body: <p>I've been wrangling with this problem for over a week with little to no progress.</p>
  
  <p>I've looked at </p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/25187926/how-to-set-selected-value-of-jquery-select2">How to set selected value of jquery select2?</a></li>
  <li><a href="https://stackoverflow.com/questions/18487056/select2-doesnt-work-when-embedded-in-a-bootstrap-modal/19574076#19574076">Select2 doesn&#39;t work when embedded in a bootstrap modal</a></li>
  <li><a href="https://stackoverflow.com/questions/14339089/populating-dropdown-with-json-result-cascading-dropdown-using-mvc3-jquery-aj">Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON</a></li>
  <li><a href="https://stackoverflow.com/questions/17957040/reset-select2-value-and-show-placeholder">Reset select2 value and show placeholder</a></li>
  <li><a href="https://github.com/select2/select2/issues/3057" rel="nofollow noreferrer">https://github.com/select2/select2/issues/3057</a></li>
  <li><a href="https://github.com/select2/select2/issues/1436" rel="nofollow noreferrer">https://github.com/select2/select2/issues/1436</a>.</li>
  </ul>
  
  <p>Finally, after looking at <a href="https://select2.org/troubleshooting/common-problems" rel="nofollow noreferrer">https://select2.org/troubleshooting/common-problems</a> </p>
  
  <p>I tried applying both the <code>dropdownParent: $('#myModal')</code> and the </p>
  
  <pre><code>// Do this before you initialize any of your modals
  $.fn.modal.Constructor.prototype.enforceFocus = function() {};
  </code></pre>
  
  <p>Neither of these fixes worked so I'm really at my wits end and ready to give up on using the modal altogether. Basically I'm getting my data back from the server in a JSON object, then using that data to populate the modal. The populating is working correctly on all the elements (several of which are select / combo boxes) except the first combobox.</p>
  
  <p>Thank you in advance for your help and sorry if the answer is posted elsewhere, but I can't find it.
  Following is the pertinent code:</p>
  
  <pre><code>&lt;!-- Modal to Add / Edit Delay parent div must have same id as value of the data-target attribute used to trigger the modal --&gt;
  &lt;div class="modal fade" id="delayAddModal" tabindex="-1" role="dialog" aria-labelledby="delayAddLabel"&gt;
      &lt;div class="modal-dialog" role="document"&gt;
          &lt;!-- Modal content --&gt;
          &lt;div class="modal-content"&gt;
              &lt;div class="modal-header"&gt;
                  &lt;!-- This "x" button is for dismissing the modal --&gt;
                  &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt;
                     &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;
                  &lt;/button&gt;
                  &lt;h4 class="modal-title" id="delayAddLabel"&gt;Add Delay&lt;/h4&gt;
              &lt;/div&gt;
              &lt;div class="modal-body"&gt;
                  &lt;p id="testActualJobTaskIdFunction"&gt;&lt;/p&gt;
                  @Html.Partial("_ActualTrainDelayAddEdit", Model.TrainDelay)
              &lt;/div&gt;
              &lt;div class="modal-footer"&gt;
                  &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt;
                  &lt;!-- call to js function--&gt;
                  &lt;button id="delayAddButton" type="button" class="btn btn-primary" data-title="Add Delay"&gt;Add Delay&lt;/button&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Partial view nested in the modal defined above (this has been trimmed down so that the elements that are updating correctly are missing). The subdivisionId is not updating correctly, however, locationId is (both are combo boxes):</p>
  
  <pre><code>@model ActualTrainDelayAddEditModel
  
  &lt;form name="delay-form" id="delay-form"&gt;
      @Html.HiddenFor(m =&gt; m.ActualTrainDelayId, new { id = "ActualTrainDelayId" })
  
      @Html.HiddenFor(m =&gt; m.ActualJobTaskId)
  
  
      @*Original:*@
      &lt;div class="form-group"&gt;
          &lt;!-- Renders floating text ("Subdivision") above the select options --&gt;
          @Html.LabelFor(m =&gt; m.SubdivisionId, new { @class = "field-label always-visible" })
  
          &lt;!-- ID for select element --&gt;
          &lt;!-- Renders select class="select" id="SubdivisionId" name="SubdivisionId"&gt;&lt;option value="4429faa8-5ad4-4adf-adde-ec7cf88ed9e9" innerHTML "Caltrain"--&gt;
          @Html.DropDownListFor(m =&gt; m.SubdivisionId, Model.AvailableSubdivisions, new { @class = "select" })
          @Html.ValidationMessageFor(m =&gt; m.SubdivisionId)
      &lt;/div&gt;
  
      &lt;!-- Location --&gt;
      &lt;div class="form-group"&gt;
          @Html.LabelFor(m =&gt; m.LocationId, new { @class = "field-label always-visible" })
          &lt;select id="LocationId" name="LocationId" class="select"&gt;
              @foreach (var loc in Model.AvailableLocations)
              {
                  &lt;option value="@loc.Id" data-milepost="@loc.Milepost"&gt;@loc.Name&lt;/option&gt;
              }
          &lt;/select&gt;
  
          @Html.ValidationMessageFor(m =&gt; m.LocationId)
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>jQuery function that is updating the modal with the data:</p>
  
  <pre><code>&lt;script&gt;
  // Do this before you initialize any of your modals
      $.fn.modal.Constructor.prototype.enforceFocus = function() {};
  
      $("#delayAddModal")
              .on("show.bs.modal",
                  function(event) {
                      var button = $(event.relatedTarget); // Button that triggered the modal 
                      var modal = $(this);
                      var title = button.data('title'); // get New title from data-title attribute
                      var delId = button.data("guid");
                      var name = button.data("name");
  
                      var conditionalVariable = 1;
  
                      var updateButtonValue = "Save Edit";
  
                      //alert(title);
  
  
                      //$("#SubdivisionId").append("&lt;option value='0'&gt;--Select State--&lt;/option&gt;");
  
                      //If add delay is clicked there will be no guid
                      if (delId == null) {
  
                          modal.find('.modal-title').text(title); // set title to Add Delay
  
                          modal.find('#delayAddButton').text("Add Delay"); // set button value to Add Delay
                          return;
  
                      }
  
                      modal.find('.modal-title').text(title); // set title to New title
                      modal.find('#delayAddButton').text(updateButtonValue); // set button value to Edit Delay
  
                      //    var button = $(event.relatedTarget);
                      //    var delId = button.data("guid");
                      //    var name = button.data("name");
                      //var modal = $(this);
  
                      $.ajax({
                          type: "GET",
                          url: "@Url.Action("GetDelayDataForEditing")/" + "?delayId=" + delId,
                          dataType: 'json',
                          //data: delId,
                          success: function(data) {
  
  
                              modal.find('');
                              //$("#SubdivisionId").change(function () {
  
                              var sub = data.SubdivisionId;
  
                              //console.log("This is the subId: "+sub);
                              //changing the subdivision changes the locations available in the location box
                              $.getJSON('@Url.Action("LocationBySubdivisionList", "TrainActivity")?id=' + sub,
                                  function(locs) {
  
                                      // the stuff that needs to happen before the parent ajax completes needs to go in here
                                      $('#IncidentNumber').val(data.IncidentNumber);
      //                                    alert("In the getJson function");
  
                                      //$("select#SubdivisionId").empty();
                                      $('select#SubdivisionId').val(data.SubdivisionId);
                                      //$('#SubdivisionId').select2('data', data.SubdivisionId);
                                      //$('select#SubdivisionId').select2('data', data.SubdivisionId);
                                      //$('#SubdivisionId').select2('data', { id: 100, a_key: 'Lorem Ipsum' });
                                      $("#SubdivisionId &gt; [value=" + data.SubdivisionId + "]")
                                          .insertBefore("#SubdivisionId &gt; :first-child");
                                      //$("#SubdivisionId").append(data.SubdivisionId);
  
                                      $('#StartMilepost').val(data.StartMilepost);
                                      $('#EndMilepost').val(data.EndMilepost);
  
  
                                      var list = $('#LocationId');
                                      list.find('option').remove();
                                      $(locs).each(function(index, loc) {
                                          list.append('&lt;option value="' +
                                              loc.Id +
                                              '" data-milepost="' +
                                              loc.Milepost +
                                              '"&gt;' +
                                              loc.Name +
                                              '&lt;/option&gt;');
                                      });
  
                                      $('select#LocationId').val(data.LocationId);
                                      $("#LocationId &gt; [value=" + data.LocationId + "]")
                                          .insertBefore("#LocationId &gt; :first-child");
                                      //$("#LocationId").append(data.LocationId);
                                      //nearestMilepost();
  
                                      $('select#DelayTypeId').val(data.DelayTypeId);
                                      $("#DelayTypeId &gt; [value=" + data.DelayTypeId + "]")
                                          .insertBefore("#DelayTypeId &gt; :first-child");
                                      //$("#DelayTypeId").append(data.DelayTypeId);
  
                                      $('select#ThirdPartyResponsibleId').val(data.ThirdPartyResponsibleId);
                                      $("#ThirdPartyResponsibleId &gt; [value=" + data.ThirdPartyResponsibleId + "]")
                                          .insertBefore("#ThirdPartyResponsibleId &gt; :first-child");
  
  
                                      $('#BeginDelayDateTime').val(parseHoursAndMinutes(data.BeginDelayDateTime));
                                      $('#EndDelayDateTime').val(parseHoursAndMinutes(data.EndDelayDateTime));
                                      $('#ResultingDelay').val(data.ResultingDelay);
                                      $('#TimeInDelay').val(data.TimeInDelay);
  
  
                                      if (data.IsServiceFailure) {
                                          $('#IsServiceFailure').iCheck('check');
                                      } else {
                                          $('#IsServiceFailure').iCheck('uncheck');
  
                                      }
  
                                      if (data.IsResolved) {
                                          $('#IsResolved').iCheck('check');
                                      } else {
                                          $('#IsResolved').iCheck('uncheck');
  
                                      }
  
                                      if (data.IsRootCauseDelay) {
                                          $('#IsRootCauseDelay').iCheck('check');
                                      } else {
                                          $('#IsRootCauseDelay').iCheck('uncheck');
  
                                      }
  
                                      $('#Comment').val(data.Comment);
  
                                      $('#SavedVisible').iCheck('uncheck');
  
                                      $('#SaveNewComment').iCheck('uncheck');
  
                                      $('#ActualTrainDelayId').val(data.ActualTrainDelayId);
  
                                      //delayExists = true;
                                      //$('button#delayAddButton').attr("id", delId);
  
                                  });
  
                              alert("Success " +
                                  "\nunparsed data: " +
                                  data +
                                  "\nStringified data: " +
                                  JSON.stringify(data) +
                                  //"\nNew JS date: " + newJavaScriptDate +
                                  //"\nDate date: " + parsedBeginDateTime +
                                  //"\nFormatted date: " + hoursAndMinutes +
                                  //"\nDisplay time: " + timeToDisplay +
                                  //"\nAJT id: " + data.ActualJobTaskId +
                                  //"\nIncident Number: " + data.IncidentNumber +
                                  "\nLocation ID: " +
                                  data.LocationId +
                                  "\nStart MP: " +
                                  data.StartMilepost +
                                  "\nEnd MP: " +
                                  data.EndMilepost +
                                  "\nDelay Type Id: " +
                                  data.DelayTypeId +
                                  "\nThird Party Resp: " +
                                  data.ThirdPartyResponsibleId +
                                  "\nSubdivision Id: " +
                                  data.SubdivisionId +
                                  "\nbegin Delay time: " +
                                  data.BeginDelayDateTime +
                                  "\nend Delay time: " +
                                  data.EndDelayDateTime +
                                  "\nresulting delay: " +
                                  data.ResultingDelay +
                                  "\ntime in delay: " +
                                  data.TimeInDelay +
                                  "\nis root cause: " +
                                  data.IsRootCauseDelay +
                                  "\nis resolved: " +
                                  data.IsResolved +
                                  "\nis service failure: " +
                                  data.IsServiceFailure +
                                  "\ncomment: " +
                                  data.Comment
                              );
  
                              //$('#delays-grid').data('kendoGrid').dataSource.read();
                              //$("#delayAddModal").modal("hide");
  
  
                          },
                          error: function() { alert("error in Delay Edit"); }
                      });
  
  
                      //modal.find(".modal-body").text("Edit the Delay at " + name + " with id " + delId);
                      //modal.find(".modal-footer #delayEditButton").data("guid", delId);
                  });
  &lt;/script&gt;
  </code></pre>