2017-02-03 64 views
0

我的問題:我必須關注插入字符後的下一個文本輸入。該輸入只能包含一個字符,特別是一個數字。更改焦點插入的值

我的解決方案(僞代碼):

onKeyUp="nextInput.focus()" 

...適用於桌面好的,但在移動,有時值在下一個字段移動(在錯誤的細胞)後寫

我的第二個解決方案:

onChange="nextInput.focus()" 

不起作用,因爲onchange事件被稱爲只有在HTML元素失去了焦點。

回答

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/

移動(野生動物園,鉻)測試和臺式機(瀏覽器,Firefox)

+0

的https: //jsfiddle.net/9u9hb839/9/不適用於Chrome Android –

0

我發現的唯一的解決方案,即工作也在移動環境:

function moveFocus(evt, id) { 
     setTimeout(function() { 
      document.getElementById(id).focus(); 
      document.getElementById(id).select(); 
     }, 100); 
}