jQuery:如果输入字段在特定时间内未填写,则清除输入字段

jQuery: Clear input field if it is not filled in certain time?

本文关键字:字段 输入 清除 定时间 如果 jQuery      更新时间:2023-09-26

使用 jquery 或 js,如果输入字段在特定时间内没有达到 x 个字符数,如何清除输入字段?

基本上,如果输入字段在 10 秒内没有达到 1 个字符,我想清除键入的任何输入。

如何计算从开始输入(第 1 个字符输入)到到达第 10 个字符的时间?

也许你应该像下面这样将其链接到keyup事件:

// ... somewhere in the ON DOM READY section, input has ID "a"
$('#a').keyup(function(){var o=$(this);// o: jQuery object referring to the current input
                         setTimeout(function(){ if (o.val().length<5) o.val('');},1000);
})

看这里: http://jsfiddle.net/1fjyezf7/.我在示例中将最小长度减少到 5 个字符。否则我的打字太慢了;-)。

您可以使用onfocus事件和setTimeout

document.getElementById("test").onfocus = function(){
    setTimeout(function(th){
        if(th.value.length <10){//If the no. of characters is less than 10 then clear the input field
         th.value = '';
        }
    }, 1000, this)//Time set is 1 second
}
<input id="test"/>