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

现在的问题是用户停留在最后一个字段中,接受鼠标并按下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!
});

其他提示

执行onBlur是否无效,因此当用户移动到下一个字段或点击其他字段时,值都会被保存?

我不知道这样的解决方案会被视为<!>“;重新发明<!>”;任何东西。正如你所说,一旦页面加载,它听起来只不过是一个简单的setTimeout。大约3,000毫秒后,它运行form.submit()。

我可能会在每次按键时重新开始倒计时,以便给予用户足够的时间进行输入。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top