Pasting multiple numbers over multiple input fields

后端 未结 5 1873
独厮守ぢ
独厮守ぢ 2020-12-17 01:58

I\'ve got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they\'ll get the 6 digit code and it

5条回答
  •  庸人自扰
    2020-12-17 02:27

    Edit

    I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.

    After looking at this for a while I added a solution which uses a hybrid between the 2. The code seems to do all that is required now.

    The Script:

    var $inputs = $(".def-txt-input");
    var intRegex = /^\d+$/;
    
    // Prevents user from manually entering non-digits.
    $inputs.on("input.fromManual", function(){
        if(!intRegex.test($(this).val())){
            $(this).val("");
        }
    });
    
    
    // Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
    $inputs.on("paste", function() {
        var $this = $(this);
        var originalValue = $this.val();
    
        $this.val("");
    
        $this.one("input.fromPaste", function(){
            $currentInputBox = $(this);
    
            var pastedValue = $currentInputBox.val();
    
            if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
                pasteValues(pastedValue);
            }
            else {
                $this.val(originalValue);
            }
    
            $inputs.attr("maxlength", 1);
        });
    
        $inputs.attr("maxlength", 6);
    });
    
    
    // Parses the individual digits into the individual boxes.
    function pasteValues(element) {
        var values = element.split("");
    
        $(values).each(function(index) {
            var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
            $inputBox.val(values[index])
        });
    };​
    

    See DEMO

提交回复
热议问题