select2 是一個可以自動補全的插件。
官網位址:http://ivaynberg.github.io/select2/
使用“Loading Remote Data”的例子,利用ajax從伺服器端獲得json資料,展現在select2上面。
發現一個問題:不能選擇這些選項。
原始代碼如下:
$('#searchTasksSelectId').select2({
width : 450,
placeholder : '任務名稱/資源名稱',
minimumInputLength : 1,
ajax : { // instead of writing the function to execute the request we
// use Select2's convenient helper
url : basePath + 'web/taskConfigure/queryTasks',
dataType : 'json',
quietMillis : 250,
data : function(term, page) {
return {
q : term, // search term
};
},
results : function(data, page) { // parse the results into the
// format expected by Select2.
// since we are using custom formatting functions we do not need
// to alter the remote JSON data
return {
results : data.items
};
},
cache : true
},
initSelection : function(element, callback) {
},
formatResult : repoFormatResult, // omitted for brevity, see the
// source of this page
formatSelection : repoFormatResult, // omitted for brevity, see the
// source of this page
dropdownCssClass : 'bigdrop', // apply css that makes the dropdown
// taller
escapeMarkup : function(m) {
return m;
} // we do not want to escape markup since we are displaying html in
// results
});
function repoFormatResult(rs) {
var markup = rs.taskName + '(ID:' + rs.taskId + ',owner:' + rs.ownUserId
+ ')';
return markup;
}
後來在網上找了一下,原因是:
Select2 使用ajax從伺服器取回資料之後,要進行點選,必須知道唯一的ID。也就是給selec2添加id屬性。
之後的代碼是:
$('#searchTasksSelectId').select2({
width : 450,
placeholder : '任務名稱/資源名稱',
minimumInputLength : 1,
id : function(rs) {
return rs.taskId;
},
ajax : { // instead of writing the function to execute the request we
// use Select2's convenient helper
url : basePath + 'web/taskConfigure/queryTasks',
dataType : 'json',
quietMillis : 250,
data : function(term, page) {
return {
q : term, // search term
};
},
results : function(data, page) { // parse the results into the
// format expected by Select2.
// since we are using custom formatting functions we do not need
// to alter the remote JSON data
return {
results : data.items
};
},
cache : true
},
initSelection : function(element, callback) {
},
formatResult : repoFormatResult, // omitted for brevity, see the
// source of this page
formatSelection : repoFormatResult, // omitted for brevity, see the
// source of this page
dropdownCssClass : 'bigdrop', // apply css that makes the dropdown
// taller
escapeMarkup : function(m) {
return m;
} // we do not want to escape markup since we are displaying html in
// results
});
參考位址:
http://stackoverflow.com/questions/15639184/cant-select-item-in-list-created-by-ui-select2
https://groups.google.com/forum/#!topic/select2/jczxIqRQp_Q