最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - In Javascript, how do I automatically move the cursor to the next text box when the current one is full? - Stack Overfl

programmeradmin10浏览0评论

Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters. How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters. How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?

Share Improve this question asked Dec 14, 2010 at 21:57 Vivian RiverVivian River 32.4k64 gold badges210 silver badges323 bronze badges 1
  • 2 You have several answers telling you how you can do this, but have you considered that you might not want to do it? Automatically changing focus is unexpected behaviour and can be confusing and frustrating for users. See uxexchange.com/questions/4303/auto-tabbing-on-form-fields for more – Day Commented Dec 14, 2010 at 22:21
Add a comment  | 

7 Answers 7

Reset to default 16

A basic implementation would be like this:

 $('#txt1').keyup(function() {
     if(this.value.length == $(this).attr('maxlength')) {
         $('#txt2').focus();
     }
 });

But there are some usability subtleties to it you may or may not care about. If you find the above to be insufficient, there are many jQuery plugins out there to do this for you.

It's called autotabbing, and there are many plugins that already exist for jquery that do this. Just google it.

If you want to know how to do it, then you bind an onkeyup event to inputs. Every time a key is released, make sure its not a functional key such as "Tab" (You should allow the user to "Shift+Tab" or "Tab" to the input without it then autotabbing to the next field.)

Then, if the input value's length exceeds the input's maxlength attribute, set the focus on the next input (in jQuery, $currentInput.next('input').focus().

None of these solutions work in straight Javascript... this snippet is a start:

document.getElementById('txt1').onkeydown = function() {
  if (this.value.length == this.maxLength)
   document.getElementById('txt2').focus();
}

But once you have entered the number, you can't go back and edit it, because as soon as you hit delete, it jumps back to txt2.

The only thing to change is make it onkeyup instead. :D

jQuery is overkill and lazy programming for the vast majority of things it is used on, and this is a great example. Unless you are already using it on the page, it is an awful lot of overhead for such a tiny task.

The idea is to handle the keydown event and check if the maximum length has been reached; if so, focus the next control.

document.getElementById('txt1').onkeydown = function() {
  if (this.value.length == this.maxLength)
    document.getElementById('txt2').focus();
}

JQuery plugin:

https://github.com/Mathachew/jquery-autotab

Simplest use:

Add class autotabbed to your inputs.

$('.autotabbed').autotab();

You could utilize jQuery UI's :focusable selector by replicating the class like this:

$.extend($.expr[':'], {
    focusable: function(element) {
        var nodeName = element.nodeName.toLowerCase(),
            tabIndex = $.attr(element, 'tabindex');
        return (/input|select|textarea|button|object/.test(nodeName)
            ? !element.disabled
            : 'a' == nodeName || 'area' == nodeName
                ? element.href || !isNaN(tabIndex)
                : !isNaN(tabIndex))
            // the element and all of its ancestors must be visible
            // the browser may report that the area is hidden
            && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
    }
});

Then you can handle it like this:

$(document).ready(function() {
    $('input[type=text]').keydown(function() {
        var $this = $(this),
            $focusables = $(':focusable'),
            current = $focusables.index(this),
            $next;

        if ($this.val().length == $this.attr('maxlength')) {
            $next = $focusables.eq(current+1).length ?$focusables.eq(current+1) : $focusables.eq(0);
                $next.focus();
        }
    });
});

See a working example here:

http://jsfiddle.net/kU6ZN/

This solution allows backward tabbing....

$("#txt1").on('input', function () {
    if (this.value.length == this.maxLength) {
        $('#txt2').focus();
    }
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论