Focus next input once reaching maxlength value

后端 未结 9 1181
梦毁少年i
梦毁少年i 2020-11-29 05:20

How can I focus the next input once the previous input has reached its maxlength value?

a: 
b: 

        
9条回答
  •  囚心锁ツ
    2020-11-29 05:34

    No jQuery used and is a very clean implementation:

    • Reads from the maxlength attribute.
    • Scales to any number of inputs inside of your container.
    • Automatically finds the next input to focus.
    • No jQuery.

    http://jsfiddle.net/4m5fg/5/

    a: b: c:

    ..

    var container = document.getElementsByClassName("container")[0];
    container.onkeyup = function(e) {
        var target = e.srcElement || e.target;
        var maxLength = parseInt(target.attributes["maxlength"].value, 10);
        var myLength = target.value.length;
        if (myLength >= maxLength) {
            var next = target;
            while (next = next.nextElementSibling) {
                if (next == null)
                    break;
                if (next.tagName.toLowerCase() === "input") {
                    next.focus();
                    break;
                }
            }
        }
        // Move to previous field if empty (user pressed backspace)
        else if (myLength === 0) {
            var previous = target;
            while (previous = previous.previousElementSibling) {
                if (previous == null)
                    break;
                if (previous.tagName.toLowerCase() === "input") {
                    previous.focus();
                    break;
                }
            }
        }
    }
    

提交回复
热议问题