autoComplete 是 jQuery 時代的經典自動完成外掛。實務上有兩種常見用法:一次載入全部候選資料在本機比對,或每次輸入都請後端即時查詢。本文示範這兩種模式,並說明如何突破它只支援 q / limit 兩個參數的限制。
適合候選資料量有限、變動不频繁的情境,例如客戶清單。
/* 客戶名稱自動匹配 */
function customerAutoComplete(){
$.ajax({
type: "GET",
url: encodeURI("/approvalajax/salesOrderApproval_findCustomerList"),
dataType: "json",
success: function(data, textStatus){
if (data != null && data.customerList != null){
$("#customerFullName").autocomplete(data.customerList, {
/** 自訂表頭 **/
tableHead: "<div><span class='col-1'>客戶編碼</span>"
+ "<span class='col-2'>客戶名稱</span></div>",
minChars: 0,
width: 310,
matchContains: "true",
autoFill: false,
extraParams: { ledger: $("#ledger").val() },
formatItem: function(row, i, max) {
return "<span class='col-1'>" + row.cusCode + "</span> "
+ "<span class='col-2'>" + row.cusName + "</span>";
},
formatMatch: function(row, i, max) { return row.cusCode + row.cusName; },
formatResult: function(row) { return row.cusName; }
}).result(function(e, data, value, sec){
/** 選中後的回呼 **/
clearCustomerInfo();
$("#customerShortName").val(data.cusAbbName);
$("#customerFullName").val(data.cusName);
$("#customerCode").val(data.cusCode);
setPLAndPCAndCP(data.cusCode); // 依客戶與帳套載入產品線等
setInventoryAutoComplete(data.cusCode); // 載入存貨編碼
}).bind("unmatch", function(){ clearCustomerInfo(); });
}
}
});
}
/** 異步請求結果 */
private Map<String, Object> ajaxResultMap;
/**
* @Description 依帳套異步加載客戶列表
*/
public String findCustomerList() throws Exception {
ajaxResultMap = new HashMap<String, Object>();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
List<ErpCustomer> list = erpDataService.findCustomerList(ledger);
ajaxResultMap.put("customerList", list);
return SUCCESS;
}
<package name="approval-ajax" extends="json-default" namespace="/approvalajax">
<action name="salesOrderApproval_*" method="{1}" class="xx.xxx.xxAction">
<result type="json">
<param name="root">ajaxResultMap</param>
<param name="contentType">text/html</param>
</result>
</action>
</package>
把 URL 直接傳給 autocomplete,外掛會自動在你輸入時發請求,並附上 q 參數。
/* 客戶名稱自動匹配 */
function customerAutoComplete(){
$("#customerFullName").autocomplete(
encodeURI("/approvalajax/salesOrderApproval_findCustomerList"), {
tableHead: "<div><span class='col-1'>客戶編碼</span>"
+ "<span class='col-2'>客戶名稱</span></div>",
minChars: 0,
width: 310,
matchContains: "true",
autoFill: false,
extraParams: { ledger: $("#ledger").val() },
dataType: 'json',
parse: function(data) {
var rows = [];
if (data == null || data.customerList == null) { return rows; }
for (var i = 0; i < data.customerList.length; i++){
rows[rows.length] = {
data: data.customerList[i],
value: data.customerList[i].cusName,
result: data.customerList[i].cusName
};
}
return rows;
},
formatItem: function(row, i, max) { /* 同上 */ },
formatMatch: function(row, i, max) { return row.cusCode + row.cusName; },
formatResult: function(row) { return row.cusName; }
}).result(function(e, data, value, sec){
clearCustomerInfo();
$("#customerShortName").val(data.cusAbbName);
$("#customerFullName").val(data.cusName);
$("#customerCode").val(data.cusCode);
$("#licensecode").val(data.licensecode);
setPLAndPCAndCP(data.cusCode);
addInventoryAutoComplete($("#detailListTbody").find("input[tdTag=inventoryCode]"));
}).bind("unmatch", function(){ clearCustomerInfo(); });
}
/** 自動填充輔助字元 */
private String q;
private Map<String, Object> ajaxResultMap;
public String findCustomerList() throws Exception {
ajaxResultMap = new HashMap<String, Object>();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// 外掛會自動把輸入內容放在 q 參數中
List<ErpCustomer> list = erpDataService.findTop5CustomerList(ledger, q);
ajaxResultMap.put("customerList", list);
return SUCCESS;
}
注意:這個外掛預設以 /n 拆分行、| 拆分欄位。若要直接解析 JSON,必須自行實作 parse 方法,否則會跳錯誤。
選中項目後可用 result 事件做後續處理:
$("#singleBirdRemote").result(function(event, data, formatted) {
// 選取後給其他控制項賦值、觸發其他事件等
});
外掛只認 q 與 limit 兩個參數,作者另外提供了 extraParams 作為擴充。問題是 extraParams 是初始化時就固定的靜態值。舉例來說,公司名稱自動完成需要同時帶上「城市」參數,而城市是使用者事後才選的,這時 extraParams 就力不從心。
解法是在外掛的 onChange 流程中插入一個自訂回呼,讓每次觸發前都能重算 options。改動只有三步。
找到 $.Autocompleter.defaults = ... 附近,補上一行:
onBegin: null,
找到 function onChange(crap, skipPrevCheck),在函式最前面插入:
function onChange(crap, skipPrevCheck) {
// 啟動 onChange 時,允許重新設定 options
if (options.onBegin) {
var op = options.onBegin(options);
if (op) {
$.extend(options, op);
}
}
if (lastKeyPressCode == KEY.DEL) { select.hide(); return; }
var currentValue = $input.val();
if (!skipPrevCheck && currentValue == previousValue) return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if (currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase) currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
}
/* 客戶名稱自動匹配 */
function customerAutoComplete(){
$("#customerFullName").autocomplete(
encodeURI("/approvalajax/salesOrderApproval_findCustomerList"), {
tableHead: "<div><span class='col-1'>客戶編碼</span>"
+ "<span class='col-2'>客戶名稱</span></div>",
minChars: 0,
width: 310,
multiple: false,
mustMatch: false,
matchContains: false,
matchSubset: false,
autoFill: false,
// 關鍵:每次觸發前動態更新 ledger
onBegin: function(options) {
options.extraParams.ledger = $("#ledger").val();
return options;
},
dataType: 'json',
parse: function(data) {
var rows = [];
if (data == null || data.customerList == null) { return rows; }
for (var i = 0; i < data.customerList.length; i++){
rows[rows.length] = {
data: data.customerList[i],
value: data.customerList[i].cusName,
result: data.customerList[i].cusName
};
}
return rows;
},
formatItem: function(row, i, max) { /* 略 */ },
formatMatch: function(row, i, max) { return row.cusCode + row.cusName; },
formatResult: function(row) { return row.cusName; }
}).result(function(e, data, value, sec){
clearCustomerInfo();
$("#customerShortName").val(data.cusAbbName);
$("#customerFullName").val(data.cusName);
$("#customerCode").val(data.cusCode);
$("#licensecode").val(data.licensecode);
setPLAndPCAndCP(data.cusCode);
}).bind("unmatch", function(){ clearCustomerInfo(); });
}
改動整理起來就是:defaults 多一個 onBegin、onChange 開頭判斷並合併回傳值、呼叫時在 onBegin 裡寫入業務邏輯。這樣一來,extraParams 甚至其他 options 都能動態調整,可謂一魚多吃。
更多 jQuery 相關內容可參考本站專題:《jQuery 視窗操作技巧總結》、《jQuery 拖拽特效與技巧總結》、《jQuery 常用插件及用法總結》、《jQuery 中 Ajax 用法總結》、《jQuery 表格操作技巧匯總》、《jQuery 擴展技巧總結》與《jQuery 選擇器用法總結》。
希望本文所述對你的 jQuery 開發有所幫助。