Gianluca Demarinis
Gianluca Demarinis

Reputation: 2191

Change focus on value inserted

My problem: I have to focus on the next text input after that a char is inserted. This input can contain only one character, specifically a number.

My solution (pseudo-code):

onKeyUp="nextInput.focus()"

... works good on desktop but on mobile, sometimes the value is written after moving on the next fields (in the wrong cell).

My second solution:

onChange="nextInput.focus()"

doesn't work because the onchange event is called only if the HTML element lost his focus.

Upvotes: 0

Views: 100

Answers (2)

Gianluca Demarinis
Gianluca Demarinis

Reputation: 2191

The only solution I found, that works also in mobile environment:

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

Upvotes: 0

mudin
mudin

Reputation: 2852

It seems working in my safari, 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;
}

Please, Check this: https://jsfiddle.net/9u9hb839/4/

EDITED:

in order to prevent to detect other keys press rather than a char, I updated my code:

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;
}

Try this: https://jsfiddle.net/9u9hb839/9/

Tested in mobile(safari, chrome) and desktop (chrome, firefox)

Upvotes: 1

Related Questions