我的问题:在插入字符后,我必须关注下一个文本输入。此输入只能包含一个字符,特别是一个数字。
我的解决方案(伪代码):
onChange="nextInput.focus()"
...在桌面上运行良好,但在移动设备上运行时,有时会在移动到下一个字段(在错误的单元格中)后写入。
我的第二个解决方案:
yyyymmdd
不起作用,因为仅当HTML元素失去焦点时才会调用onchange事件。
答案 0 :(得分:1)
似乎在我的野生动物园工作,iphone:
$("#first").on('keyup', function(e){
if(isCharacterKeyPress(e)){
$("#second").focus();
console.log(e);
}
});
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
请检查:https://jsfiddle.net/9u9hb839/4/
<强>编辑:强>
为了防止检测其他按键而不是char,我更新了我的代码:
var keypressed = false;
$("#first").on('keyup', function(e){
console.log('keyup');
if(keypressed){
$("#second").focus();
}
keypressed = false;
});
$("#first").on('keypress', function(e){
console.log('keypress');
keypressed = isCharacterKeyPress(e);
});
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
试试这个:https://jsfiddle.net/9u9hb839/9/
在手机(safari,chrome)和桌面(chrome,firefox)中测试
答案 1 :(得分:0)
我发现的唯一解决方案,也适用于移动环境:
function moveFocus(evt, id) {
setTimeout(function () {
document.getElementById(id).focus();
document.getElementById(id).select();
}, 100);
}