Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - How to focus next input field on keypress

I am making a mobile application. I want to implement this function where on pressing the key, the next input field is focused. I tried many things but none seem to be working. This is my code. I tried using onClick but when i touch it, it goes to the next field.

<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />
<input type="number" class="mobile-verify pass" maxlength="1" name="code[]" />

I want a pure Jquery or Javascript solution. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about:

$('input.mobile-verify.pass').on('keyup', function() {
    if ($(this).val()) {
        $(this).next().focus();
    }
});

So on key up, if there is a value, focus the next. Using keyup allows you to validate the contents rather than skipping right away. They might switch to number mode on iOS for example which would trigger the focus if you simply use keypress.

Codepen: http://codepen.io/anon/pen/qaGKzk


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...