当用户完成输入而不是打开键时运行javascript函数?

时间:2021-02-05 03:40:34

I want to trigger an ajax request when the user has finished typing in a text box. I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.

我希望在用户完成输入文本框后触发ajax请求。我不希望每次用户输入一个字母时它都运行这个函数,因为这会导致很多ajax请求,但是我也不希望它们必须点击enter按钮。

Is there a way so I can detect when the user has finished typing and then do the ajax request?

是否有一种方法可以让我检测用户何时完成输入,然后执行ajax请求?

Using jQuery here! Dave

使用jQuery这里!戴夫

22 个解决方案

#1


503  

So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.

我猜完成输入意味着你停一会儿,比如5秒。记住这一点,让我们在用户释放密钥时启动计时器,并在按下密钥时清除它。我决定问题中的输入将是my# input。

Making a few assumptions...

做几个假设……

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

#2


297  

The chosen answer above does not work.

上面所选的答案不起作用。

Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

因为排字计时器有时会被多次设置(在快速排字者触发下键之前按两次键),所以它不能正确清除。

The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

下面的解决方案解决了这个问题,并将在完成OP之后调用X秒。它也不再需要冗余的keydown函数。我还添加了一个检查,以便在输入为空时不会发生函数调用。

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

#3


65  

It's just one line with underscore.js debounce function:

只是一行下划线。js防反跳功能:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

This basically says doSomething 500 milliseconds after I stop typing.

基本上就是在我停止输入500毫秒后做一些事情。

For more info: http://underscorejs.org/#debounce

更多信息:http://underscorejs.org/ #防反跳

#4


39  

Yes, you can set a timeout of say 2 seconds on each and every key up event which will fire an ajax request. You can also store the XHR method and abort it on subsequent key press events so that you save bandwith even more. Here's something I've written for an autocomplete script of mine.

是的,您可以为每一个将触发ajax请求的键up事件设置一个超时,比如2秒。您还可以存储XHR方法,并在随后的按键事件中中止它,这样您就可以保存更多的bandwith。这是我为我的自动完成脚本写的东西。

var timer;
var x;

$(".some-input").keyup(function () {
    if (x) { x.abort() } // If there is an existing XHR, abort it.
    clearTimeout(timer); // Clear the timer so we don't end up with dupes.
    timer = setTimeout(function() { // assign timer a new timeout 
        x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
    }, 2000); // 2000ms delay, tweak for faster/slower
});

Hope this helps,

希望这有助于

Marko

Marko

#5


16  

var timer;
var timeout = 1000;

$('#in').keyup(function(){
    clearTimeout(timer);
    if ($('#in').val) {
        timer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, timeout);
    }
});

full example here: http://jsfiddle.net/ZYXp4/8/

完整的例子:http://jsfiddle.net/ZYXp4/8/

#6


9  

I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.

我喜欢超现实梦境的答案,但我发现我的“doneTyping”功能会在每一个按键上都激活,也就是说,如果你真的快速地输入“Hello”;当您停止输入时,函数将不会只触发一次,而是触发5次。

The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:

问题是,javascript的setTimeout函数似乎没有覆盖或终止任何已设置的旧超时,但是如果您自己执行它,它就会工作!所以我在setTimeout之前添加了一个clearTimeout调用,如果设置了typingTimer,如下所示:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').on("keyup", function(){
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').on("keydown", function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!

N.B.我本想在超现实梦的答案上加上这句话,但我是一个新用户,没有足够的声誉。对不起!

#7


7  

Modifying the accepted answer to handle additional cases such as paste:

修改已接受的答案以处理其他情况,如粘贴:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 2 second for example
var $input = $('#myInput');

// updated events 
$input.on('input propertychange paste', function () {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);      
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

#8


4  

Well, strictly speaking no, as the computer cannot guess when the user has finished typing. You could of course fire a timer on key up, and reset it on every subsequent key up. If the timer expires, the user hasn't typed for the timer duration - you could call that "finished typing".

严格地说没有,因为电脑无法猜测用户什么时候完成了输入。当然,你可以在键上启动一个计时器,并在以后的每个键上重置它。如果计时器过期,用户还没有输入计时器持续时间——您可以将其称为“完成输入”。

If you expect users to make pauses while typing, there's no way to know when they are done.

如果您希望用户在输入时暂停,则无法知道它们何时完成。

(Unless of course you can tell from the data when they are done)

(当然,除非你能从数据中分辨出来)

#9


4  

I don't think keyDown event is necessary in this case (please tell me why if I'm wrong). In my (non-jquery) script similar solution looks like that:

我认为在这种情况下不需要keyDown事件(请告诉我为什么我错了)。在我的(非jquery)脚本中类似的解决方案如下:

var _timer, _timeOut = 2000; 



function _onKeyUp(e) {
    clearTimeout(_timer);
    if (e.keyCode == 13) {      // close on ENTER key
        _onCloseClick();
    } else {                    // send xhr requests
        _timer = window.setTimeout(function() {
            _onInputChange();
        }, _timeOut)
    }

}

It's my first reply on Stack Overflow, so I hope this helps someone, someday:)

这是我对Stack Overflow的第一个回复,所以我希望有一天这能帮助到某人。

#10


2  

SOLUTION:

解决方案:

I was implementing the search at my listing and need it to be ajax based. That mean that on every key change searched results should be updated and displayed. This working results in so much ajax calls sent to server, which is not a good thing. After some working I made an approach to ping server when client stops typing.

我在我的列表中实现了搜索,需要它是基于ajax的。这意味着,在每个关键字更改时,搜索结果都应该更新和显示。这个工作导致了大量ajax调用发送到服务器,这不是一件好事。经过一些工作之后,我在客户端停止输入时使用了ping服务器。

The solution worked for me is:

对我起作用的解决方案是:

$(document).ready(function() {

$('#yourtextfield').keyup(function() {
s = $('#yourtextfield').val();
setTimeout(function() { 
        if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
            $.ajax({
                type: "POST",
                url: "yoururl",
                data: 'search=' + s,
                cache: false,
                beforeSend: function() {
                   // loading image
                },
                success: function(data) {
                    // Your response will come here
                }
            })
        }
    }, 1000); // 1 sec delay to check.

    }); // End of  keyup function

    }); // End of document.ready

You have noticed that there is no need of using any timer while implementing this.

您已经注意到,在实现此功能时不需要使用任何计时器。

I am sure, this will help others.

我相信,这将帮助其他人。

Ata

Ata

#11


1  

You can use the onblur event to detect when the textbox loses focus: https://developer.mozilla.org/en/DOM/element.onblur

您可以使用onblur事件检测文本框何时失去焦点:https://developer.mozilla.org/en/DOM/element.onblur

That's not the same as "stops typing", if you care about the case where the user types a bunch of stuff and then sits there with the textbox still focused.

这和“停止输入”是不一样的,如果你关心用户输入一堆东西,然后坐在那里,文本框仍然集中。

For that I would suggest tying a setTimeout to the onclick event, and assuming that after x amount of time with no keystrokes, the user has stopped typing.

为此,我建议将setTimeout绑定到onclick事件上,并假设在没有按键的情况下经过x段时间后,用户已停止输入。

#12


1  

This is the a simple JS code I wrote:

这是我写的一个简单的JS代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

#13


1  

I feel like the solution is somewhat a bit simpler with the input event:

我觉得对于输入事件,解决方案稍微简单一些:

var typingTimer;
var doneTypingInterval = 500;

$("#myInput").on("input", function () {
    window.clearTimeout(typingTimer);
    typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});

function doneTyping () {
    // code here
}

#14


1  

Both top 2 answers doesn't work for me. So, here is my solution:

以上两个答案对我都不适用。所以,我的解决方案是:

var timeout = null;

$('#myInput').keyup(function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        //do stuff here
    }, 500);
});

#15


0  

Once you detect focus on the text box, on key up do a timeout check, and reset it each time it's triggered.

一旦您检测到焦点在文本框上,在key up上做一个超时检查,并在每次触发它时重置它。

When the timeout completes, do your ajax request.

超时完成后,执行ajax请求。

#16


0  

If you are looking for a specific length (such as a zipcode field):

如果您正在寻找特定的长度(例如zipcode字段):

$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
        //make ajax request here after.
    }
  });

#17


0  

Not sure if my needs are just kind of weird, but I needed something similar to this and this is what I ended up using:

我不确定我的需求是不是有点奇怪,但我需要类似的东西,这就是我最后使用的:

$('input.update').bind('sync', function() {
    clearTimeout($(this).data('timer'));            
    $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
        if(x.success != true) {
            triggerError(x.message);    
        }
    }, 'json');
}).keyup(function() {
    clearTimeout($(this).data('timer'));
    var val = $.trim($(this).val());
    if(val) {
        var $this = $(this);
        var timer = setTimeout(function() {
            $this.trigger('sync');
        }, 2000);
        $(this).data('timer', timer);
    }
}).blur(function() {
    clearTimeout($(this).data('timer'));     
    $(this).trigger('sync');
});

Which allows me to have elements like this in my application:

这让我在我的申请中有这样的元素:

<input type="text" data-url="/controller/action/" class="update">

Which get updated when the user is "done typing" (no action for 2 seconds) or goes to another field (blurs out of the element)

当用户“完成输入”(2秒内不执行操作)或进入另一个字段(从元素中模糊出来)时更新

#18


0  

If you need wait until user is finished with typing use simple this:

如果您需要等待用户完成输入,请使用以下简单的方法:

$(document).on('change','#PageSize', function () {
    //Do something after new value in #PageSize       
});

Complete Example with ajax call - this working for my pager - count of item per list:

ajax调用的完整示例——这适用于我的寻呼机——每个列表项的计数:

$(document).ready(function () {
    $(document).on('change','#PageSize', function (e) {
        e.preventDefault();
        var page = 1;
        var pagesize = $("#PageSize").val();
        var q = $("#q").val();
        $.ajax({
            url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
            data: { q: q, pagesize: pagesize, page: page },
            type: 'post',
            datatype: "json",
            success: function (data) {
                $('#tablecontainer').html(data);
               // toastr.success('Pager has been changed', "Success!");
            },
            error: function (jqXHR, exception) {
                ShowErrorMessage(jqXHR, exception);
            }
        });  
    });
});    

#19


0  

agree with the @going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored

同意@going的回答。另一个对我有用的类似的解决方案是下面这个。唯一的区别是我使用.on(“input”…)而不是keyup。这只捕获了输入中的更改。其他键如Ctrl、Shift等被忽略

var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on input change, start the countdown

$('#myInput').on("input", function() {    
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function(){
        // doSomething...
    }, doneTypingInterval);
});

#20


0  

Why not just use onfocusout?

为什么不直接使用onfocusout?

https://www.w3schools.com/jsreF/event_onfocusout.asp

https://www.w3schools.com/jsreF/event_onfocusout.asp

If it's a form, they will always leave focus of every input field in order to click the submit button so you know no input will miss out on getting its onfocusout event handler called.

如果它是一个表单,它们会始终保留每个输入字段的焦点,以便单击submit按钮,这样您就知道没有输入会错过调用它的onfocusout事件处理程序。

#21


0  

I just figured out a simple code to wait for user to finish typing:

我刚刚想出了一个简单的代码等待用户完成输入:

step 1.set time out to null then clear the current timeout when the user is typing.

步骤1。将时间设置为null,然后在用户输入时清除当前超时。

step 2.trigger clear timeout to the variable define before keyup event is triggered.

步骤2。在触发keyup事件之前,触发对变量定义的清除超时。

step 3.define timeout to the variable declared above;

步骤3定义上面声明的变量的超时;

<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>

javascript code

javascript代码

var textInput = document.getElementById('input');
var textdata = document.querySelector('.data');
// Init a timeout variable to be used below
var timefired = null;

// Listen for keystroke events
// Init a timeout variable to be used below
var timefired = null;// Listen for keystroke events
textInput.onkeyup = function (event) {
clearTimeout(timefired);
timefired = setTimeout(function () {
    textdata.innerHTML = 'Input Value:'+ textInput.value;
  }, 600);
};

#22


-1  

Wow, even 3 comments are pretty correct!

哇,连3个评论都是相当正确的!

  1. Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect

    空的输入不是跳过函数调用的原因,例如,我在重定向之前从url中删除浪费的参数

  2. .on ('input', function() { ... }); should be used to trigger keyup, paste and change events

    .on ('input', function(){…});是否应该使用触发键、粘贴和更改事件?

  3. definitely .val() or .value must be used

    必须使用.val()或.value

  4. You can use $(this) inside event function instead of #id to work with multiple inputs

    您可以在事件函数中使用$(this)而不是#id来处理多个输入

  5. (my decision) I use anonymous function instead of doneTyping in setTimeout to easily access $(this) from n.4, but you need to save it first like var $currentInput = $(this);

    (我的决定)我使用匿名函数,而不是在setTimeout中使用doneTyping来轻松地从n访问$(this)。但是您需要先保存它,比如var $currentInput = $(this);

#1


503  

So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.

我猜完成输入意味着你停一会儿,比如5秒。记住这一点,让我们在用户释放密钥时启动计时器,并在按下密钥时清除它。我决定问题中的输入将是my# input。

Making a few assumptions...

做几个假设……

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

#2


297  

The chosen answer above does not work.

上面所选的答案不起作用。

Because typingTimer is occassionaly set multiple times (keyup pressed twice before keydown is triggered for fast typers etc.) then it doesn't clear properly.

因为排字计时器有时会被多次设置(在快速排字者触发下键之前按两次键),所以它不能正确清除。

The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won't happen if your input is empty.

下面的解决方案解决了这个问题,并将在完成OP之后调用X秒。它也不再需要冗余的keydown函数。我还添加了一个检查,以便在输入为空时不会发生函数调用。

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

#3


65  

It's just one line with underscore.js debounce function:

只是一行下划线。js防反跳功能:

$('#my-input-box').keyup(_.debounce(doSomething , 500));

This basically says doSomething 500 milliseconds after I stop typing.

基本上就是在我停止输入500毫秒后做一些事情。

For more info: http://underscorejs.org/#debounce

更多信息:http://underscorejs.org/ #防反跳

#4


39  

Yes, you can set a timeout of say 2 seconds on each and every key up event which will fire an ajax request. You can also store the XHR method and abort it on subsequent key press events so that you save bandwith even more. Here's something I've written for an autocomplete script of mine.

是的,您可以为每一个将触发ajax请求的键up事件设置一个超时,比如2秒。您还可以存储XHR方法,并在随后的按键事件中中止它,这样您就可以保存更多的bandwith。这是我为我的自动完成脚本写的东西。

var timer;
var x;

$(".some-input").keyup(function () {
    if (x) { x.abort() } // If there is an existing XHR, abort it.
    clearTimeout(timer); // Clear the timer so we don't end up with dupes.
    timer = setTimeout(function() { // assign timer a new timeout 
        x = $.getJSON(...); // run ajax request and store in x variable (so we can cancel)
    }, 2000); // 2000ms delay, tweak for faster/slower
});

Hope this helps,

希望这有助于

Marko

Marko

#5


16  

var timer;
var timeout = 1000;

$('#in').keyup(function(){
    clearTimeout(timer);
    if ($('#in').val) {
        timer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, timeout);
    }
});

full example here: http://jsfiddle.net/ZYXp4/8/

完整的例子:http://jsfiddle.net/ZYXp4/8/

#6


9  

I like Surreal Dream's answer but I found that my "doneTyping" function would fire for every keypress, i.e. if you type "Hello" really quickly; instead of firing just once when you stop typing, the function would fire 5 times.

我喜欢超现实梦境的答案,但我发现我的“doneTyping”功能会在每一个按键上都激活,也就是说,如果你真的快速地输入“Hello”;当您停止输入时,函数将不会只触发一次,而是触发5次。

The problem was that the javascript setTimeout function doesn't appear to overwrite or kill the any old timeouts that have been set, but if you do it yourself it works! So I just added a clearTimeout call just before the setTimeout if the typingTimer is set. See below:

问题是,javascript的setTimeout函数似乎没有覆盖或终止任何已设置的旧超时,但是如果您自己执行它,它就会工作!所以我在setTimeout之前添加了一个clearTimeout调用,如果设置了typingTimer,如下所示:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example

//on keyup, start the countdown
$('#myInput').on("keyup", function(){
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#myInput').on("keydown", function(){
    clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
    //do something
}

N.B. I would have liked to have just added this as a comment to Surreal Dream's answer but I'm a new user and don't have enough reputation. Sorry!

N.B.我本想在超现实梦的答案上加上这句话,但我是一个新用户,没有足够的声誉。对不起!

#7


7  

Modifying the accepted answer to handle additional cases such as paste:

修改已接受的答案以处理其他情况,如粘贴:

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 2 second for example
var $input = $('#myInput');

// updated events 
$input.on('input propertychange paste', function () {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);      
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

#8


4  

Well, strictly speaking no, as the computer cannot guess when the user has finished typing. You could of course fire a timer on key up, and reset it on every subsequent key up. If the timer expires, the user hasn't typed for the timer duration - you could call that "finished typing".

严格地说没有,因为电脑无法猜测用户什么时候完成了输入。当然,你可以在键上启动一个计时器,并在以后的每个键上重置它。如果计时器过期,用户还没有输入计时器持续时间——您可以将其称为“完成输入”。

If you expect users to make pauses while typing, there's no way to know when they are done.

如果您希望用户在输入时暂停,则无法知道它们何时完成。

(Unless of course you can tell from the data when they are done)

(当然,除非你能从数据中分辨出来)

#9


4  

I don't think keyDown event is necessary in this case (please tell me why if I'm wrong). In my (non-jquery) script similar solution looks like that:

我认为在这种情况下不需要keyDown事件(请告诉我为什么我错了)。在我的(非jquery)脚本中类似的解决方案如下:

var _timer, _timeOut = 2000; 



function _onKeyUp(e) {
    clearTimeout(_timer);
    if (e.keyCode == 13) {      // close on ENTER key
        _onCloseClick();
    } else {                    // send xhr requests
        _timer = window.setTimeout(function() {
            _onInputChange();
        }, _timeOut)
    }

}

It's my first reply on Stack Overflow, so I hope this helps someone, someday:)

这是我对Stack Overflow的第一个回复,所以我希望有一天这能帮助到某人。

#10


2  

SOLUTION:

解决方案:

I was implementing the search at my listing and need it to be ajax based. That mean that on every key change searched results should be updated and displayed. This working results in so much ajax calls sent to server, which is not a good thing. After some working I made an approach to ping server when client stops typing.

我在我的列表中实现了搜索,需要它是基于ajax的。这意味着,在每个关键字更改时,搜索结果都应该更新和显示。这个工作导致了大量ajax调用发送到服务器,这不是一件好事。经过一些工作之后,我在客户端停止输入时使用了ping服务器。

The solution worked for me is:

对我起作用的解决方案是:

$(document).ready(function() {

$('#yourtextfield').keyup(function() {
s = $('#yourtextfield').val();
setTimeout(function() { 
        if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
            $.ajax({
                type: "POST",
                url: "yoururl",
                data: 'search=' + s,
                cache: false,
                beforeSend: function() {
                   // loading image
                },
                success: function(data) {
                    // Your response will come here
                }
            })
        }
    }, 1000); // 1 sec delay to check.

    }); // End of  keyup function

    }); // End of document.ready

You have noticed that there is no need of using any timer while implementing this.

您已经注意到,在实现此功能时不需要使用任何计时器。

I am sure, this will help others.

我相信,这将帮助其他人。

Ata

Ata

#11


1  

You can use the onblur event to detect when the textbox loses focus: https://developer.mozilla.org/en/DOM/element.onblur

您可以使用onblur事件检测文本框何时失去焦点:https://developer.mozilla.org/en/DOM/element.onblur

That's not the same as "stops typing", if you care about the case where the user types a bunch of stuff and then sits there with the textbox still focused.

这和“停止输入”是不一样的,如果你关心用户输入一堆东西,然后坐在那里,文本框仍然集中。

For that I would suggest tying a setTimeout to the onclick event, and assuming that after x amount of time with no keystrokes, the user has stopped typing.

为此,我建议将setTimeout绑定到onclick事件上,并假设在没有按键的情况下经过x段时间后,用户已停止输入。

#12


1  

This is the a simple JS code I wrote:

这是我写的一个简单的JS代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

#13


1  

I feel like the solution is somewhat a bit simpler with the input event:

我觉得对于输入事件,解决方案稍微简单一些:

var typingTimer;
var doneTypingInterval = 500;

$("#myInput").on("input", function () {
    window.clearTimeout(typingTimer);
    typingTimer = window.setTimeout(doneTyping, doneTypingInterval);
});

function doneTyping () {
    // code here
}

#14


1  

Both top 2 answers doesn't work for me. So, here is my solution:

以上两个答案对我都不适用。所以,我的解决方案是:

var timeout = null;

$('#myInput').keyup(function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        //do stuff here
    }, 500);
});

#15


0  

Once you detect focus on the text box, on key up do a timeout check, and reset it each time it's triggered.

一旦您检测到焦点在文本框上,在key up上做一个超时检查,并在每次触发它时重置它。

When the timeout completes, do your ajax request.

超时完成后,执行ajax请求。

#16


0  

If you are looking for a specific length (such as a zipcode field):

如果您正在寻找特定的长度(例如zipcode字段):

$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
        //make ajax request here after.
    }
  });

#17


0  

Not sure if my needs are just kind of weird, but I needed something similar to this and this is what I ended up using:

我不确定我的需求是不是有点奇怪,但我需要类似的东西,这就是我最后使用的:

$('input.update').bind('sync', function() {
    clearTimeout($(this).data('timer'));            
    $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
        if(x.success != true) {
            triggerError(x.message);    
        }
    }, 'json');
}).keyup(function() {
    clearTimeout($(this).data('timer'));
    var val = $.trim($(this).val());
    if(val) {
        var $this = $(this);
        var timer = setTimeout(function() {
            $this.trigger('sync');
        }, 2000);
        $(this).data('timer', timer);
    }
}).blur(function() {
    clearTimeout($(this).data('timer'));     
    $(this).trigger('sync');
});

Which allows me to have elements like this in my application:

这让我在我的申请中有这样的元素:

<input type="text" data-url="/controller/action/" class="update">

Which get updated when the user is "done typing" (no action for 2 seconds) or goes to another field (blurs out of the element)

当用户“完成输入”(2秒内不执行操作)或进入另一个字段(从元素中模糊出来)时更新

#18


0  

If you need wait until user is finished with typing use simple this:

如果您需要等待用户完成输入,请使用以下简单的方法:

$(document).on('change','#PageSize', function () {
    //Do something after new value in #PageSize       
});

Complete Example with ajax call - this working for my pager - count of item per list:

ajax调用的完整示例——这适用于我的寻呼机——每个列表项的计数:

$(document).ready(function () {
    $(document).on('change','#PageSize', function (e) {
        e.preventDefault();
        var page = 1;
        var pagesize = $("#PageSize").val();
        var q = $("#q").val();
        $.ajax({
            url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
            data: { q: q, pagesize: pagesize, page: page },
            type: 'post',
            datatype: "json",
            success: function (data) {
                $('#tablecontainer').html(data);
               // toastr.success('Pager has been changed', "Success!");
            },
            error: function (jqXHR, exception) {
                ShowErrorMessage(jqXHR, exception);
            }
        });  
    });
});    

#19


0  

agree with the @going 's answer. Another similar solution that worked for me is the one below. The only difference is that I am using .on("input"...) instead of keyup. This only captures changes in the input. other keys like Ctrl, Shift etc. are ignored

同意@going的回答。另一个对我有用的类似的解决方案是下面这个。唯一的区别是我使用.on(“input”…)而不是keyup。这只捕获了输入中的更改。其他键如Ctrl、Shift等被忽略

var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms (5 seconds)

//on input change, start the countdown

$('#myInput').on("input", function() {    
    clearTimeout(typingTimer);
    typingTimer = setTimeout(function(){
        // doSomething...
    }, doneTypingInterval);
});

#20


0  

Why not just use onfocusout?

为什么不直接使用onfocusout?

https://www.w3schools.com/jsreF/event_onfocusout.asp

https://www.w3schools.com/jsreF/event_onfocusout.asp

If it's a form, they will always leave focus of every input field in order to click the submit button so you know no input will miss out on getting its onfocusout event handler called.

如果它是一个表单,它们会始终保留每个输入字段的焦点,以便单击submit按钮,这样您就知道没有输入会错过调用它的onfocusout事件处理程序。

#21


0  

I just figured out a simple code to wait for user to finish typing:

我刚刚想出了一个简单的代码等待用户完成输入:

step 1.set time out to null then clear the current timeout when the user is typing.

步骤1。将时间设置为null,然后在用户输入时清除当前超时。

step 2.trigger clear timeout to the variable define before keyup event is triggered.

步骤2。在触发keyup事件之前,触发对变量定义的清除超时。

step 3.define timeout to the variable declared above;

步骤3定义上面声明的变量的超时;

<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>

javascript code

javascript代码

var textInput = document.getElementById('input');
var textdata = document.querySelector('.data');
// Init a timeout variable to be used below
var timefired = null;

// Listen for keystroke events
// Init a timeout variable to be used below
var timefired = null;// Listen for keystroke events
textInput.onkeyup = function (event) {
clearTimeout(timefired);
timefired = setTimeout(function () {
    textdata.innerHTML = 'Input Value:'+ textInput.value;
  }, 600);
};

#22


-1  

Wow, even 3 comments are pretty correct!

哇,连3个评论都是相当正确的!

  1. Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect

    空的输入不是跳过函数调用的原因,例如,我在重定向之前从url中删除浪费的参数

  2. .on ('input', function() { ... }); should be used to trigger keyup, paste and change events

    .on ('input', function(){…});是否应该使用触发键、粘贴和更改事件?

  3. definitely .val() or .value must be used

    必须使用.val()或.value

  4. You can use $(this) inside event function instead of #id to work with multiple inputs

    您可以在事件函数中使用$(this)而不是#id来处理多个输入

  5. (my decision) I use anonymous function instead of doneTyping in setTimeout to easily access $(this) from n.4, but you need to save it first like var $currentInput = $(this);

    (我的决定)我使用匿名函数,而不是在setTimeout中使用doneTyping来轻松地从n访问$(this)。但是您需要先保存它,比如var $currentInput = $(this);