2014-10-04 136 views
0

即時通訊使用jquery Select2,select2完美無缺。但是我想要什麼時,頁面加載默認值應該從控制器加載。Select2加載默認值使用遠程數據的單選元素中的值

是的,我已經做過谷歌和是的這個問題已經發布了很多次,我不能相當讓我的頭圍繞它..所以,這就是爲什麼我需要在這方面的幫助。

這裏是選擇2 JS代碼:

/*----------- Select2 DropDown Common Script -------------------------*/ 
//For ServerSide Script 
function commonSelect2(selector,url,id,text,minInputLength,placeholder){ 
    selector.select2({ 
     minimumInputLength:minInputLength, 
     placeholder:placeholder, 
     ajax: { 
      type:"post", 
      url: url, 
      dataType: 'json', 
      quietMillis: 100, 
      data: function(term, page) { 
       return { 
        term: term, //search term 
        page_limit: 10 // page size 
       }; 
      }, 
      initSelection : function (element, callback) { 
       var data = {id: element.val(), text: element.val()}; 
       callback(data); 
      }, 
      results: function(data, page) { 
       var newData = []; 
       $.each(data, function (index,value) { 
        newData.push({ 
         id: value[id], //id part present in data 
         text: value[text] //string to be displayed 
        }); 
       }); 
       return { results: newData }; 
      } 
     } 
    }); 
} 

,在這裏我是如何從PHP文件

{{*The Selector for Selecting the User Group*}} 
var selector = $('#selectGroup'); 
var url = "{{base_url()}}admin/usersManageUsers/loadAllUserGroups/"; 
var id = "GroupID"; 
var text = "GroupName"; 
var minInputLength = 0; 
var placeholder = "Select User Group"; 
commonSelect2(selector,url,id,text,minInputLength,placeholder); 
//End of the CommonSelect2 function 

我已經加入了initselection()函數調用它,但我不知道如果我這樣做寫得對嗎?

最後我在html select2隱藏的輸入標記中添加了這個。

我試圖在網上搜索,但看起來像我沒有得到任何地方。

回答

0

我的錯誤。 我在ajax裏面定義了initSelection。應該在ajax之外定義它。

現在阿賈克斯之後定義initSelection()

ajax: { 
    type:"post", 
    url: url, 
    dataType: 'json', 
    quietMillis: 100, 
    data: function(term, page) { 
     return { 
      term: term, //search term 
      page_limit: 10 // page size 
     }; 
    }, 
    results: function(data, page) { 
     var newData = []; 
     $.each(data, function (index,value) { 
      newData.push({ 
       id: value[id], //id part present in data 
       text: value[text] //string to be displayed 
      }); 
     }); 
     return { results: newData }; 
    } 
}, 
initSelection : function (element, callback) { 
    var data = {id: element.val(), text: element.val()}; 
    callback(data); 
}