专注于下一个输入(jQuery) [英] focusing on next input (jquery)

查看:80
本文介绍了专注于下一个输入(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个输入,每个输入取一个数字.我想做的是,一旦设置了数字,就会自动将焦点设置到下一个输入.它们都具有输入"类.

I've got four inputs that each take one number. What I want to do is set the focus automatically to the next input once the number has been set. They all have the class "inputs".

这不太奏效:

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

            $(this).next().focus();
        });

推荐答案

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

I would suggest setting maxlength as 1 to each textbox and switch to next one once the val.length and the maxlength is same.

演示

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

编辑:花了一些时间进行以下操作(尚未完全测试,但基本测试效果很好)

Spent some time for the following (not fully tested, but basic tests worked fine)

   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.

代码:

$(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;
        }
    });
});

演示

这篇关于专注于下一个输入(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆