如何将下一个输入字段集中在按键上
我正在制作移动应用程序。 我想实现这个function,在按下键的同时,下一个输入字段被聚焦。 我尝试了很多东西,但似乎都没有。 这是我的代码。 我尝试使用onClick但是当我触摸它时,它会转到下一个字段。
我想要一个纯Jquery或Javascript解决方案。 提前致谢。
怎么样:
$('input.mobile-verify.pass').on('keyup', function() { if ($(this).val()) { $(this).next().focus(); } });
所以在关键时,如果有值,请关注下一个。 使用keyup可以validation内容而不是立即跳过。 他们可能会在iOS上切换到数字模式,例如,如果你只是使用按键,它会触发焦点。
Codepen: http ://codepen.io/anon/pen/qaGKzk
使用.next()
和.trigger()
:
$(".mobile-verify.pass").on("keypress", function(e){ $(this).next().trigger("focus"); })
使用 。 keypress()和.focus()
片段:
$(document).ready(function (){ $("input.mobile-verify.pass").keypress(function(){ $(this).next().trigger('focus'); //or $(this).next().focus(); }); });
JavaScript和事件keypress
和focus
以及关键数字validation:
var elems = [].slice.call(document.querySelectorAll('.mobile-verify.pass')); elems.forEach(function(el, i, array) { el.onkeypress = function(event) { // Validate key is a number var keycode = event.which; if (!(event.shiftKey === false && (keycode === 46 || keycode === 8 || keycode === 37 || keycode === 39 || (keycode >= 48 && keycode <= 57)))) { return; } var nextInput = i + 1; if (nextInput < array.length) { array[nextInput].focus(); } }; });
其他人已经编写了解决方案。 我只是想补充一下这个部分
[].slice.call
是什么解决了我的问题。 我无法聚焦元素,因为它是Element类型,而不是HtmlElement。 但不知何故,这部分代码将我的querySelectorAll元素列表转换为HtmlElements。
谢谢Yosvel Quintero