我正在为我们客户的项目编写一个脚本,当您达到特定输入的最大字符数时,该脚本会自动将您导入下一个输入字段。由于某种原因,输入值的返回值应该小于它应该的值,因此当在“阈值”上方输入一个额外的字符时,会选中“下一个”输入。
这是我的脚本来观看输入值 - ofc,如果有更好的方法请指教:) -
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事件没有读取初始值有关,但我不知道如何修复它。任何帮助真的很感激。
我在控制台中记录结果:
答案 0 :(得分:2)
问题是,onkeypress
会在您想要它之前触发。您可以简单地将onkeypress
替换为onkeyup
,这样您就可以确保在检查时<input>
元素value
设置正确。
答案 1 :(得分:0)
是的,它会减少一个,只需在长度检查上使用+1。这是beacuse onkeypress
事件在字段更新之前执行,这意味着使用e.preventDefault()
字母将不会出现在字段中。否则你可以使用onkeyup
。
答案 2 :(得分:0)
使用onkeyup
代替onkeypress
onkeyup
被触发
答案 3 :(得分:0)
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
return false; // this is prevent the third value being entered
}