输入值onkeydown返回不正确的值(少了一个) [英] Input value onkeydown returns incorrect value (one less)

查看:151
本文介绍了输入值onkeydown返回不正确的值(少了一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为客户项目的脚本编写脚本,当您达到特定输入的最大字符数时,该脚本会自动将您跳转到下一个输入字段.由于某种原因,输入值返回的值比应该返回的值小一个,因此,当在阈值"上方输入一个额外的字符时,会跳至下一个"输入.

I'm working on a script for our client's project that autotabs you onto the next input field when you've hit the maximum character count for a particular input. For some reason the input value is returning one less than it should be, and therefore tabs to the 'next' input when an extra character is entered above the 'threshold'.

这是我的脚本,用于监视输入值-ofc,如果有更好的方法,请告知:)-

Here's my script to watch the inputs value - ofc, if there is a better way please advise :) -

var watchLength = function (watch) {
    watch.onkeypress = function () {
        var nextInput = getNextSibling(this);
        console.log(this.getAttribute('data-autotab-length'));
        console.log(this.value.length);
        if (this.value.length == this.getAttribute('data-autotab-length')) {
            nextInput.focus();
            console.log('Limit reached here');
        }
    };
};

和一个jsFiddle到工作输入.第一个输入限制为"2"个字符,但是当您键入3时,它将跳至下一个输入.我认为这与keypress/keydown事件不读取初始值有关,但是我不知道如何解决它.任何帮助都非常感激.

And a jsFiddle to the working input. The first input is limited to '2' characters, but when you type in 3 it jumps to the next input. I think this is something to do with the keypress/keydown event not reading the initial value, but I'm at a loss of how to fix it. Any help really appreciated.

我正在控制台中记录结果:

I'm logging the results in the Console:

http://jsfiddle.net/qdnCZ/

推荐答案

问题是,onkeypress将在您希望的时候触发.您只需将onkeypress替换为onkeyup,就可以确保在检查时正确设置了<input>元素value.

The Problem is, that onkeypress will fire before you want it to. You can simply replace onkeypress by onkeyup, that way you make sure that the <input> elements value is set correctly the time you check it.

请参阅: http://jsfiddle.net/qdnCZ/1/

这篇关于输入值onkeydown返回不正确的值(少了一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆