2013-08-20 38 views
6

我正在使用select2插件來加載遠程數據。我正在使用返回JSON數據的aspx頁面,並將其分配給select2插件。用戶從select2文本框中選擇一些值後,我強制頁面回發。回發後,我使用下面的代碼重新加載設置在select2文本框中的文本。無法調用val()如果initSelection()未在select2插件中定義錯誤

var data = { "PatientID": "XYX", "Email": "[email protected]" }; 

      $('#e6').select2('val', '123'); 

但系統拋出以下錯誤:cannot call val() if initSelection() is not defined

即使我定義的init,我不能設置值。我正在使用以下代碼。請在回發後幫我設置select2文本框的值。 !

$(document).ready(function() { 
     $("#e6").select2({ 
      placeholder: "Search for a movie", 
      minimumInputLength: 1, 
      ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
       url: "data.aspx", 
       dataType: 'json', 
       quietMillis: 1000, 
       data: function (term, page) { 
        return { 
         name: term 
        }; 
       }, 
       initSelection: function (element, callback) { 
        var data = { "PatientID": "XYX", "Email": "[email protected]" }; 
        callback(data); 
       }, 

       results: function (data) { 
        var results = []; 
        $.each(data, function (index, item) { 
         results.push({ 
          id: item['Email'], 
          text: item['PatientID'] 
         }); 
        }); 
        return { 
         results: results 
        }; 
       }, 
      }, 
     }); 

    }); 

    window.onload = function() { 
     var data = { "PatientID": "XYX", "Email": "[email protected]" }; 
     //When this is called system is throwing error 
     //This code is required to show the value in select2 textbox after the post back 
     $('#e6').select2('val', data); 
    } 

    $(document).ready(function() { 
     $("#e6").on("select2-selecting", function (e) { 
      //alert("selecting val=" + e.val + " choice=" + JSON.stringify(e.choice)); 
      var id = document.getElementById('<%= savebtn.ClientID %>'); 
      document.getElementById('<%= hdnFld.ClientID %>').value = e.val; 
      id.value = e.val; 
      //causes post back 
      id.click(); 

     }); 
    }); 
+4

'initSelection'不應該在'ajax'屬性中。 – user1983983

回答

5

你犯錯我已經遇到這個問題,我看見你question.Then我讀選擇二和源泉的德API文檔,我是wrong.Pleas平行initSelection將與ajax.like這樣的:

$("#e6").select2({ 
     placeholder: "Search for a movie", 
     minimumInputLength: 1, 
     initSelection: function (element, callback) { 
       var data = { "PatientID": "XYX", "Email": "[email protected]" }; 
       callback(data); 
      }, 
     ajax: { // instead of writing the function to execute the request we use Select2's convenient helper 
      url: "data.aspx", 
      dataType: 'json', 
      quietMillis: 1000, 
      data: function (term, page) { 
       return { 
        name: term 
       }; 
      }, 


      results: function (data) { 
       var results = []; 
       $.each(data, function (index, item) { 
        results.push({ 
         id: item['Email'], 
         text: item['PatientID'] 
        }); 
       }); 
       return { 
        results: results 
       }; 
      }, 
     }, 
    }); 
相關問題