在用户仍在键入时异步获取输入值

时间:2019-11-15 10:53:36

标签: javascript html

我有一个这样的输入字段

 <input type="text" placeholder="Search" id="search" />

,并希望在用户仍在键入时阅读内容,然后在搜索字符串匹配时显示数据。我想我需要一个异步函数,但是我不知道如何继续处理字符串。

async function readSearchString(){
return document.getElementById("search").value;
}


function processString(cell, string)
{
   // Keep doing this
   var searchString = await readSearchString();
   if (cell.includes(searchString))
   {
       cell.visibility = "hidden";
   }  
}

我是否需要以无限循环的方式运行整个函数,以保持用户输入的效果?

2 个答案:

答案 0 :(得分:2)

您可以根据需要使用onchangeonkeyuponkeydown等输入事件。

function processString()
{
   var searchString = document.getElementById("search").value;
   console.log('Search key :'+ searchString);
   // You can do your search code here
   /* 
   if (cell.includes(searchString))
   {
       cell.visibility = "hidden";
   }
   */
}
<input type="text" placeholder="Search" id="search"  onkeyup="processString()">

答案 1 :(得分:0)

我认为您想要这样的东西。我曾经做过的事

var searchRequest = null; //prevent multiple unnecessary requests to the server.

$(function () {
    var minlength = 3;

    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null) 
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "sample.php",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});