专注于下一个输入(jquery)

dom*_*ino 20 jquery

我有四个输入,每个输入一个数字.我想要做的是在设置数字后自动将焦点设置为下一个输入.他们都有类"输入".

这不太奏效:

$(".inputs").keydown(function () {

            $(this).next().focus();
        });
Run Code Online (Sandbox Code Playgroud)

Sel*_*gam 49

我建议将maxlength设置为每个文本框1,并切换到下一个文本框,val.length并且maxlength相同.

DEMO

$(".inputs").keyup(function () {
    if (this.value.length == this.maxLength) {
      $(this).next('.inputs').focus();
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:花了一些时间用于以下(未完全测试,但基本测试工作正常)

   1. Allowing just numeric chars  
   2. Allow some control like del, backspace, e.t.c
   3. Backspace on empty textbox will move to prev textbox
   4. charLimit var to dynamically decide how many char you want to restrict.
Run Code Online (Sandbox Code Playgroud)

码:

$(function() {
    var charLimit = 1;
    $(".inputs").keydown(function(e) {

        var keys = [8, 9, /*16, 17, 18,*/ 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];

        if (e.which == 8 && this.value.length == 0) {
            $(this).prev('.inputs').focus();
        } else if ($.inArray(e.which, keys) >= 0) {
            return true;
        } else if (this.value.length >= charLimit) {
            $(this).next('.inputs').focus();
            return false;
        } else if (e.shiftKey || e.which <= 48 || e.which >= 58) {
            return false;
        }
    }).keyup (function () {
        if (this.value.length >= charLimit) {
            $(this).next('.inputs').focus();
            return false;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 哇这太棒了.我将它与click()结合使用,因此当用户选择已填充的文本框时,它会重置该值.现在,如果用户选择一个填充的输入并键入一个数字,它会关注下一个输入而不是下一个输入(假设所有文本框都已填充).在一个理想的情况下,我想在键入新数字之前不需要删除该数字(它会自动替换它).我可以看到,如果实现超过1个字符限制,这将成为问题.只是我的想法.无论如何,click()将为我做伎俩:) (2认同)

Jiv*_*ngs 5

无论它是什么,都将得到下一个元素。您可能想要:

$(".inputs").keyup(function () {
  $(this).next(".inputs").focus();
});
Run Code Online (Sandbox Code Playgroud)

同样,按下键而不是按下键,否则更改太快。


小智 5

尝试这个

jQuery.extend(jQuery.expr[':'], {
    focusable: function (el, index, selector) {
        return $(el).is('a, button, :input,[tabindex]');
    }
});
$(document).on('keypress', 'input,select', function (e) {
    if (e.which == 13) {
        e.preventDefault();
        // Get all focusable elements on the page
        var $canfocus = $(':focusable');
        var index = $canfocus.index(document.activeElement) + 1;
        if (index >= $canfocus.length) index = 0;
        $canfocus.eq(index).focus();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 我见过的模仿 &lt;tab&gt; 按键的最佳解决方案。由于某种原因,“$(':focusable')”选择器在不扩展 jQuery 的情况下为我工作,所以我需要的唯一代码是“//Get all ...”注释后面的四行。 (2认同)