输入完毕后如何提交表格?(JavaScript异步)

克里斯蒂安·莫拉莱斯

在用户停止键入半秒钟后,我需要提交一个表单提交。

您应该保持输入的重点,并且如果再输入几个字符,它仍应继续提交。

我更喜欢香草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>

我希望用户能够输入,并在输入完成后一秒钟提交搜索。焦点模糊应保留在输入上,以便它们可以继续键入/搜索。

麦威尔逊

基本上,您需要捕获最后键入的键与您的特定等待时间之间的时间。在这种情况下,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" />

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章