Focus next input once reaching maxlength value

后端 未结 9 1180
梦毁少年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:44

    You can watch for input in the fields and test its value:

    $("input").bind("input", function() {
        var $this = $(this);
        setTimeout(function() {
            if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
                $this.next("input").focus();
        },0);
    });
    

    Working demo.

    The setTimeout is there to ensure the code will only run after the input is completed and the value updated. Binding input ensures most types of input will trigger the event, including key presses, copy/paste (even from mouse) and drag & drop (though in this case, the latter won't work, since the focus was on the draggable, not the droppable).

    Note: on some older browsers, you might also need to bind propertychange.


    If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.

    To do that, you might need to remove the maxlength attribute using JavaScript (to be able to capture the full input), and implement that functionality yourself. I made a small example, relevant parts below:

    $("input").each(function() {
        var $this = $(this);
        $(this).data("maxlength", $this.prop("maxlength"));
        $(this).removeAttr("maxlength");
    })
    

    This removes the attribute, but saves it in data, so you can access it later.

    function spill($this, val) {
        var maxlength = $this.data("maxlength");
        if ( val.length >= maxlength ) {
            $this.val(val.substring(0, maxlength));
            var next = $this.next("input").focus();
            spill(next, val.substring(maxlength));
        }
        else
            $this.val(val);
    }
    

    Here the max length logic is reintroduced in JavaScript, as well as getting the "discarded" part and using it in a recursive call to spill. If there's no next element, the call to data will return undefined and the loop will stop, so the input will be truncated in the last field.

提交回复
热议问题