gpt4 book ai didi

javascript - 键盘不活动 x 英里秒后自动提交表单

转载 作者:搜寻专家 更新时间:2023-10-31 08:09:03 24 4
gpt4 key购买 nike

在我的表单中,我有一组输入框,用户可以在其中输入值。更改其中一个框时,表单会自动提交。

但是,现在的问题是用户停留在最后一个字段中,拿起鼠标并按下 OK 按钮(另一种形式),而没有先离开文本框。更改事件不会被触发,旧的、不正确的值会传递到下一页。

我想在键盘处于非事件状态几毫秒后触发 onchange 事件。就像大多数自动完成插件一样。
我想我可以实现一个计时器,它在您输入输入字段时开始计时,并在每次处理击键时重置,然后当它达到零时触发 onchange 事件。

我不想重新发明轮子,想知道是否有这样的功能。
有什么建议吗?

最佳答案

我遇到了类似的问题并创建了一个当前在内部应用程序中使用的 jQuery 插件。它应该在用户完成输入后触发更改事件。

如果您不使用 jQuery,代码仍然适用于其他任何东西。

jQuery.fn.handleKeyboardChange = function(nDelay)
{
// Utility function to test if a keyboard event should be ignored
function shouldIgnore(event)
{
var mapIgnoredKeys = {
9:true, // Tab
16:true, 17:true, 18:true, // Shift, Alt, Ctrl
37:true, 38:true, 39:true, 40:true, // Arrows
91:true, 92:true, 93:true // Windows keys
};
return mapIgnoredKeys[event.which];
}

// Utility function to fire OUR change event if the value was actually changed
function fireChange($element)
{
if( $element.val() != jQuery.data($element[0], "valueLast") )
{
jQuery.data($element[0], "valueLast", $element.val())
$element.trigger("change");
}
}

// The currently running timeout,
// will be accessed with closures
var timeout = 0;

// Utility function to cancel a previously set timeout
function clearPreviousTimeout()
{
if( timeout )
{
clearTimeout(timeout);
}
}

return this
.keydown(function(event)
{
if( shouldIgnore(event) ) return;
// User pressed a key, stop the timeout for now
clearPreviousTimeout();
return null;
})
.keyup(function(event)
{
if( shouldIgnore(event) ) return;
// Start a timeout to fire our event after some time of inactivity
// Eventually cancel a previously running timeout
clearPreviousTimeout();
var $self = $(this);
timeout = setTimeout(function(){ fireChange($self) }, nDelay);
})
.change(function()
{
// Fire a change
// Use our function instead of just firing the event
// Because we want to check if value really changed since
// our previous event.
// This is for when the browser fires the change event
// though we already fired the event because of the timeout
fireChange($(this));
})
;
}

用法:

$("#my_input").handleKeyboardChange(300).change(function()
{
// value has changed!
});

关于javascript - 键盘不活动 x 英里秒后自动提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com