Joe
Joe

Reputation: 817

Select2 initSelection Text value not showing up

I've been looking at some of the other SO questions trying to figure out the issue with my code... I'm using an <input type='hidden' ...></input> field to store the ID of a selected individual on a jQuery select2 drop-down. When I return to the page, I'd like the name of the last individual selected to show up. I am able to have the value attribute saved, and when the drop-down is expanded - the proper name is selected. However, the actual name isn't displayed; just an empty select

enter image description here

Here's my initialization. approvers param is a JSON obj with the list of individuals

var self = this;

self.supervisorsDDL.select2({
  placeholder: "Select Supervisor",
  minimumInputLength: 0,
  width: 150,
  data: {
    results: approvers.Data,
    text: 'FullName',
    id: 'EmployeeID'
  },
  id: function (e) {
    if (e)
      return e.EmployeeID;
  },
  formatResult: function (e) {
    if (e)
      return e.FullName;
  },
  formatSelection: function (e) {
    if (e)
      return e.FullName;
  },
  initSelection: function (item, callback) {
    if (item.val() > 0) {
      var eid = item.val();
      var name, obj;
      $.get(
        self.jsonUrl,
        { method: "GetApproverNameByEmployeeId", employeeId: eid },
        function (data, textStatus) {
          if (data.Success) {
            name = data.Data;
          }
        }
      );
      obj = { EmployeeID: eid, FullName: name };
      callback(obj);
    }
  } // Set the ID for initSelection
}).select2("val", self.selectedItemHidden.val());

Both supervisorsDDL and selectedItemHidden are hidden fields, using the value attribute to hold the ID. Redundant yes, but easier and saves time for the task at hand.

Upvotes: 1

Views: 2533

Answers (1)

asawyer
asawyer

Reputation: 17808

You are calling the callback before the name value is set in the ajax response handler. Move the two lines to there and it should be fine.

initSelection: function (item, callback) {
    if (item.val() > 0) {
      var eid = item.val();
      var name, obj;
      $.get(
        self.jsonUrl,
        { method: "GetApproverNameByEmployeeId", employeeId: eid },
        function (data, textStatus) {
          if (data.Success) {
            name = data.Data;
            //call the callback now that the ajax data is ready
            obj = { EmployeeID: eid, FullName: name };
            callback(obj);
          }
        }
      );
      // moved
      //obj = { EmployeeID: eid, FullName: name };
      //callback(obj);
    }
  }

Here is a working example from one of my projects:

initSelection: function (element, callback) {
  var id = '@Model.Id';
  if (id === null) return;
  $.getJSON('@Url.HttpRouteUrl("DefaultApi", new { controller = "Search" })', {
    'id': id
   }, function (data) {
     //called in the ajax handler
     callback(data);
   });
 }

Upvotes: 2

Related Questions