資料輸入量大的後台系統,讓使用者按 Enter 就能跳到下一欄,比用 Tab 鍵順手得多。本文示範怎麼自動排出欄位的跳轉順序。
做法是頁面載入後先掃過所有元素,把 text 輸入框與 select 收集成一個陣列,然後給每個元素掛上一個自訂屬性指向下一個的索引,最後統一綁定 keydown 事件。這樣不必手寫死每個欄位的順序,新增欄位時也不用改 JS。
<script type="text/javascript">
window.onload = function(){
var list = new Array();
// 收集所有 text 輸入框與 select
for (var i = 5; i < document.all.length; i++) {
if (document.all[i].type == "text" || document.all[i].tagName == "SELECT")
list.push(i);
}
// 依序串起 nextFocusIndex
for (var i = 0; i < list.length - 1; i++) {
document.all[list[i]].setAttribute("nextFocusIndex", list[i+1]);
document.all[list[i]].onkeydown = JumpToNext;
}
// 最後一個欄位則指向 submit 按鈕
for (var i = list.length - 1; i < document.all.length; i++) {
if (document.all[i].type == "button") {
document.all[list[list.length-1]].setAttribute("nextFocusIndex", i);
document.all[list[list.length-1]].onkeydown = JumpToNext;
break;
}
}
document.all[list[0]].focus(); // 起始焦點
};
function JumpToNext(){
if (event.keyCode == 13) { // Enter
var nextFocusIndex = this.getAttribute("nextFocusIndex");
document.all[nextFocusIndex].focus();
}
}
</script>
<input id="A" name="A" type="text" />
<input id="B" name="B" type="text" />
<input id="C" name="C" type="text" />
<input id="D" name="D" type="text" />
<input id="E" name="E" type="text" />
<select id="S1" name="S1"><option>1</option><option>2</option></select>
<select id="S2" name="S2"><option>1</option><option>2</option></select>
這份程式碼用了不少已退場的 API:document.all 是 IE 專屬、event.keyCode 已標記為不建議使用,而且 JumpToNext 裡的 event 與 this 都依賴全域物件,風格相當老派。用標準寫法重寫會清爽很多:
document.addEventListener('DOMContentLoaded', function(){
var fields = document.querySelectorAll('input[type="text"], select');
fields.forEach(function(el, i){
el.addEventListener('keydown', function(e){
if (e.key === 'Enter' && fields[i + 1]) {
e.preventDefault(); // 避免觸發表單送出
fields[i + 1].focus();
}
});
});
fields[0].focus();
});
用 querySelectorAll 取代 document.all、用 e.key === 'Enter' 取代 keyCode,再補上 preventDefault() 避免 Enter 順手把表單送出去——這個細節是原實作漏掉的,實務上很容易造成使用者按 Enter 後表單直接 reload。