当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当用户在文本框中输入完成时,我想触发一个ajax请求。我不希望它在每次用户键入一封信时运行该函数,因为这会导致大量的ajax请求,但我也不希望他们不得不按回车键。
是否有一种方法,让我可以检测当用户已经完成输入,然后做ajax请求?
在这里使用jQuery !
当前回答
我只是想出了一个简单的代码,等待用户完成输入:
步骤1。将超时设置为空,然后在用户输入时清除当前超时。
步骤2。触发keyup事件之前定义的变量的清除超时。
步骤3.为上面声明的变量定义timeout;
<input type="text" id="input" placeholder="please type" style="padding-left:20px;"/>
<div class="data"></div>
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);
};
其他回答
如果您正在寻找特定的长度(例如邮政编码字段):
$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
//make ajax request here after.
}
});
下面是一个解决方案,它在不输入1秒后触发,但在输入为空白时也会立即触发。这在用户删除输入查询后清除搜索结果时非常有用。此解决方案还支持复制和粘贴到搜索框中。$(() =>{…});在简单的Jquery术语中,包装代码的顶部部分仅仅意味着“在页面加载时执行此操作”。
var searchTimer;
var searchInterval = 1000;
$(() => {
$('#search-box').on('input', (event) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
searchContacts(event.target.value);
}, (event.target.value.length > 0) ? searchInterval : 0);
});
});
function searchContacts(val) {
console.log('searching: ' + val);
}
简单易懂。
var mySearchTimeout;
$('#ctl00_mainContent_CaseSearch').keyup(function () {
clearTimeout(mySearchTimeout);
var filter = $(this).val();
mySearchTimeout = setTimeout(function () { myAjaxCall(filter); }, 700);
return true;
});
const inText = document.getElementById('inText') const outText = document.getElementById('outText') Const delay = 1000 让计时器 inText。addEventListener('input', code => { clearTimeout(计时器); timer = setTimeout(x => { outText。innerHTML = inText.value },延迟,代码) }) <textarea id='inText'>编辑这个和 <pre id='outText'>在你停止输入一秒钟后看到结果</pre>
哇,甚至有3条评论都是正确的!
Empty input is not a reason to skip function call, e.g. I remove waste parameter from url before redirect .on ('input', function() { ... }); should be used to trigger keyup, paste and change events definitely .val() or .value must be used You can use $(this) inside event function instead of #id to work with multiple inputs (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);
编辑我看到有些人不理解没有复制粘贴就绪代码的指示。在这里你
var typingTimer;
// 2
$("#myinput").on('input', function () {
// 4 3
var input = $(this).val();
clearTimeout(typingTimer);
// 5
typingTimer = setTimeout(function() {
// do something with input
alert(input);
}, 5000);
});