[英]How to submit a form after you're done typing? (JavaScript async)
在用戶停止鍵入半秒鍾后,我需要提交一個表單提交。
您應該保持輸入的重點,並且如果再輸入幾個字符,它仍然可以繼續提交。
我更喜歡香草JS,但jQuery也可以。
我嘗試使用onKeydown
事件將超時設置為半秒,然后使用了preventDefault()
和form.submit()
let searchText = document.getElementById('search_input'); searchText.onkeypress = function(e) { //alert("key down"); var event = e || window.event; var charCode = event.which || event.keycode; if (charCode == '13') { fnFillGrid(); return false; } } function fnFillGrid() { console.log('Lala'); }
<form action="#"> Search: <input id="search_input" type="search" name="q"> </form>
我希望用戶能夠在輸入完畢后一秒鍾內輸入內容,以提交搜索。 焦點模糊應保留在輸入上,以便它們可以繼續鍵入/搜索。
這將觸發onkeyup
,我發現這是啟動自動搜索的最佳方法,如下所示:
let searchText = document.getElementById('search_input'); searchText.addEventListener("keyup", search); let timeout = null; function search() { if (timeout) { window.clearTimeout(timeout); } timeout = setTimeout(function () { fnFillGrid(); }, 500); } function fnFillGrid() { console.log('Lala'); }
<form action="#"> Search: <input id="search_input" type="search" name="q"> </form>
基本上,您需要捕獲最后鍵入的鍵與您的特定等待時間之間的時間。 在這種情況下,POST請求在無輸入1秒鍾后執行。 這將是一個真實的示例(發布到jsonplaceholder
來模擬POST請求)。 您可以檢查網絡標簽(在開發工具中)以進行觀看。
還應該在這里指出不推薦使用KeyboardEvent.which
(請參閱https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which )
const postMessage = async (message) => { const response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ title: 'title', body: message, userId: 1 }), headers: { "Content-type": "application/json; charset=UTF-8" } }); return response.json(); } let time = null; const textBox = document.getElementById('myTextbox'); textBox.addEventListener('keyup', async (e) => { time = new Date().getTime(); setTimeout( async () => { const currentTime = new Date().getTime(); const timeDiff = currentTime - time; if (timeDiff >= 1000) { const response = await postMessage(textBox.value); console.log('response', response); } }, 1000); });
<input type="text" id="myTextbox" />
該解決方案基於兩個想法:
async
POST請求。 對於我們的第一個目標,我們將使用addEventListener
並偵聽keyup
事件。 當用戶釋放鍵盤上的鍵時,會發生此事件。
對於第二個目標,我們需要捕獲上次keyup
事件之間的時間,並將其與WAITING_TIME
常量進行比較,例如500 ms。
另外,我們將使用async function
聲明來定義fnFillGrid
異步函數。 這將作為一個Promise
返回一個AsyncFunction
對象,該對象將使用async function
返回的值進行解析,或者被async function
內部拋出的未捕獲異常拒絕。 fnFillGrid
也將實現fetch()
方法,該方法使我們能夠發出類似於XMLHttpRequest
網絡請求。 主要區別在於fetch()
方法使用Promises
,它啟用了更簡單,更簡潔的API,避免了回調地獄,並且必須記住XMLHttpRequest
的復雜API。
現在,我們可以調用await()
運算符以等待響應Promise
。
這里有一個功能片段:
const WAITING_TIME = 500; let startTime; let searchText = document.getElementById('search_input'); searchText.addEventListener('keyup', async(e) => { startTime = new Date().getTime(); setTimeout(async() => { let currentTime = new Date().getTime(); let timeDiff = currentTime - startTime; if (timeDiff >= WAITING_TIME) { const response = await fnFillGrid(searchText.value); console.log('response', response); } }, WAITING_TIME); }); async function fnFillGrid(message) { let result = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify({ query: message, }), headers: { "Content-type": "application/json; charset=UTF-8" } }); return result.json(); }
<form action="#"> Search: <input id="search_input" type="search" name="q"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.