表單中輸入框按 Enter 鍵會觸發預設提交行為,常導致誤送。本文提供多種攔截策略,從簡單到完整方案。
<form onkeydown="return event.key !== 'Enter'">
<input type="text" name="q">
<button type="submit">搜尋</button>
</form>
<form id="searchForm">
<input type="text" name="q" placeholder="輸入關鍵字...">
<button type="submit">搜尋</button>
</form>
<script>
document.getElementById('searchForm').addEventListener('keydown', function(e) {
// 允許 textarea、contenteditable、select 內的 Enter
const tag = e.target.tagName.toLowerCase();
const isTextInput = tag === 'input' && !['textarea', 'submit', 'button', 'reset'].includes(e.target.type);
if (e.key === 'Enter' && isTextInput) {
e.preventDefault(); // 阻止表單提交
return false;
}
});
function preventFormSubmitOnEnter(formSelector, options = {}) {
const {
allowTextarea = true,
allowShiftEnter = true, // Shift+Enter 換行
allowCtrlEnter = false, // Ctrl+Enter 送出
onSubmit = null // 自訂送出處理
} = options;
const form = document.querySelector(formSelector);
if (!form) return;
form.addEventListener('keydown', function(e) {
if (e.key !== 'Enter') return;
const target = e.target;
const tag = target.tagName.toLowerCase();
const type = target.type?.toLowerCase();
// 允許的情況
if (tag === 'textarea' && allowTextarea) return true;
if (tag === 'input' && ['submit', 'button', 'reset', 'image', 'file'].includes(type)) return true;
if (e.shiftKey && allowShiftEnter) return true;
if (e.ctrlKey && allowCtrlEnter) return true;
// 攔截:阻止預設提交
e.preventDefault();
// 可選:觸發自訂送出
if (onSubmit) {
onSubmit(new FormData(form), e);
}
});
}
// 使用
preventFormSubmitOnEnter('#searchForm', {
allowTextarea: true,
allowShiftEnter: true,
onSubmit: (formData) => {
fetch('/api/search', { method: 'POST', body: formData })
.then(r => r.json())
.then(renderResults);
}
});
$('#searchForm').on('keydown', 'input[type="text"]', function(e) {
if (e.keyCode === 13) { // Enter
e.preventDefault();
return false;
}
});
// 或整個表單
$('#searchForm').on('keydown', function(e) {
if (e.keyCode === 13 && $(e.target).is('input:not([type="submit"],[type="button"],[type="textarea"])')) {
e.preventDefault();
}
});
<form id="loginForm">
<input type="email" name="email" required>
<input type="password" name="password" required>
<!-- 改用 button type="button",不觸發預設提交 -->
<button type="button" id="loginBtn">登入</button>
</form>
<script>
document.getElementById('loginBtn').addEventListener('click', async () => {
const form = document.getElementById('loginForm');
if (!form.checkValidity()) {
form.reportValidity(); // 顯示瀏覽器原生驗證提示
return;
}
try {
const res = await fetch('/api/login', {
method: 'POST',
body: new FormData(form)
});
if (res.ok) window.location.href = '/dashboard';
} catch (err) {
console.error(err);
}
});
// 仍保留 Enter 提交功能(在最後一個輸入框)
form.addEventListener('keydown', e => {
if (e.key === 'Enter' && e.target === form.querySelector('input:last-of-type')) {
document.getElementById('loginBtn').click();
}
});
| 情況 | 處理方式 |
|---|---|
| 含 textarea 需換行 | 排除 textarea 或允許 Shift+Enter |
| 多步驟精靈表單 | 每步驟獨立 form,用 JS 控制顯示/隱藏 |
| 自動完成/選單選取觸發 Enter | 檢查 e.isComposing 或 e.target.hasAttribute('list') |
| 無障礙:語音輸入、輔助技術 | 測試 NVDA/VoiceOver,確保不阻擋正常操作 |
form.onkeydown="return event.key!=='Enter'"e.preventDefault()button type="button" + 手動 fetch 提交,完全掌控流程checkValidity()/reportValidity())