2014-10-04 77 views
1

我使用select2插件作爲文本框的自動完成。自動完成對數據庫中的員工視圖進行ajax調用。除非用戶打開網絡表單編輯記錄,否則一切都很好。我需要select2控件加載最初保存在記錄中的值,而不管它是否存在於列表中。當我打開編輯表單時,select2控件是空白的。我知道我可以加載這個值,如果它是從ajax調用中返回的json數據,但是如果它不是?我可以看到initSelection中的值,但我不知道如何設置控件文本/值。用原始值填充jquery select2

長話短說,我正在做ajax調用的視圖可能會或可能沒有原始的員工價值。例如,如果員工最初是從視圖中選擇的,但是留給了其他分支機構/代理機構,則視圖將不再顯示。我仍然需要在控件中顯示原始值。希望這是有道理的。這是我的代碼。我可以在initSelection中看到原始值,但不知道如何在控件中獲得它:

var URL = '@Url.Action("GetEmployees", "AssetAssignment")'; 
    var originalValue = ""; 

    $('#AssignedTo').select2({ 
     placeholder: "Type an MJB employee name or county...", 
     minimumInputLength: 3, 
     ajax: { 
      url: URL, 
      dataType: 'json', 
      type: "GET", 
      quietMillis: 50, 
      data: function (term) { 
       return { term: term }; 
      }, 
      results: function (data) { 
       return { results: data.data }; 
      } 
     }, 
     id: function (object) { 
      // store the text vs the id 
      return object.text; 
     },  
     createSearchChoice: function (term, data) { 
      //Allow manually entered text in drop down. 
      if ($(data).filter(function() { 
       return this.text.localeCompare(term)===0; 
      }).length===0) { 
       return { id: "", text: term, county: "" }; 
      } 
     }, 
     initSelection: function (element, callback) { 
      var id = $(element).val(); 
      if (id !== "") { 
       //var id = element.val(); 
       //var text = element.data('option'); 
       //var data = { id: id, text: text }; 
       //callback(data); 
       //alert(JSON.stringify(data)) 
       originalValue = id; 
      } 
     }, 
     formatResult: employeeFormatResult, 
     formatSelection: employeeFormatSelection 
    }); 

    // get other values from the selected item and put them in the appropriate controls 
    $('#AssignedTo').change(function() { 
     var id = $('#AssignedTo').select2('data').id; 
     var county = $('#AssignedTo').select2('data').county; 
     $('#AssignedToEmployeeId').val(id); 
     $('#AssignedToEmployeeCounty').val(county); 
    }); 

}); 

function employeeFormatResult(data) { 
    var markup = "<table class='select2-result'><tr>"; 
    markup += "<td class='select2-result-id'>" + $.trim(data.id) + "</td>"; 
    markup += "<td class='select2-result-text'>" + data.text + "</td>"; 
    markup += "<td class='select2-result-county'>" + data.county + "</td>"; 
    markup += "</tr></table>"; 
    return markup; 
} 

function employeeFormatSelection(data) { 
    return data.text; 
} 

回答

1

它的數字。在我提出問題後,我一直在研究這個問題超過一天半和五分鐘。我必須設置該值:

if (originalValue.length > 0) 
    $("#AssignedTo").select2("data", { id: originalValue, text: originalValue }); 

這對我有用,因爲我不在乎原始值是否匹配由ajax調用返回的任何內容。