表單中按 Enter 鍵是否觸發提交,瀏覽器有既定規則。理解規則、善用原生機制、輔以最小 JS 干預,能優雅解決「搜尋框要提交、複雜表單防誤觸」的雙重需求。
| 條件 | Enter 是否提交 |
|---|---|
表單內有 <input type="submit"> 或 <button type="submit"> | ✅ 是 |
表單只有一個 <input type="text">(無論按鈕類型) | ✅ 是 |
<button> 無 type:IE 默認 type=button,Firefox/Chrome 默認 type=submit | ⚠️ 不一致 |
textarea、select、radio/checkbox | 不影響規則(但 Firefox 下 Enter 會觸發 radio/checkbox 選取) |
<input type="image"> | 等同 type="submit"(不推薦,改用 CSS 背景圖) |
<form action="post.php" method="post">
<input type="text" name="name">
<input type="text" style="display:none"> <!-- 破壞「唯一文字框」條件 -->
</form>
<input type="text" name="name" onkeydown="if(event.keyCode===13) return false;">
<form id="searchForm" action="/search" method="get">
<input type="hidden" /> <!-- 破壞單一文字框規則 -->
<input type="text" name="q" onkeydown="if(event.keyCode===13){ doSearch(); return false; }">
</form>
<script>
function doSearch() {
const q = document.querySelector('[name="q"]').value;
fetch('/api/search?q=' + encodeURIComponent(q)).then(...);
}
</script>
<button type="submit">、<button type="button">(取消/重置)required:HTML5 原生驗證攔截空值提交form.addEventListener('submit', e => {
if (!form.checkValidity()) { e.preventDefault(); return; }
// 可選:AJAX 提交
e.preventDefault();
submitViaAjax(new FormData(form));
});
| 需求 | 推薦做法 |
|---|---|
| 搜尋框:Enter 觸發搜尋 | 保留原生提交,或隱藏欄位 + JS 攔截改 AJAX |
| 單一輸入框:不想提交 | 加隱藏 input[type=text](最穩健) |
| 複雜表單:防誤觸 | 明確 button type + required + JS submit 事件統一處理 |
| 跨瀏覽器一致性 | 所有 button 必加 type,不依賴預設值 |
tabindex="-1" aria-hidden="true" 避免螢幕閱讀器誤讀掌握原生規則,用最小代碼成本解決問題,才是前端工程師的智慧。