Pasting multiple numbers over multiple input fields

后端 未结 5 1878
独厮守ぢ
独厮守ぢ 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条回答
  •  猫巷女王i
    2020-12-17 02:28

    You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.

    As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.

    Here is one possible solution:

    function handleCharacter(event) {
        var $input = $(this),
            index = getIndex($input),
            digit = $input.val().slice(0,1),
            rest = $input.val().slice(1),
            $next;
    
        if (rest.length > 0) {
            $input.val(digit);  // trim input value to just one character
            $next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
    
            if ($next.length > 0) {
                $next.val(rest);  // push the rest of the value into the next input
                $next.focus();
                handleCharacter.call($next, event);  // run the same code on the next input
            }
        }
    }
    
    function handleBackspace(event) {
        var $input = $(this),
            index = getIndex($input),
            $prev;
    
        // if the user pressed backspace and the input is empty
        if (event.which === 8 && !$(this).val()) {
            $prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
            $prev.focus();
        }
    }
    
    function getIndex($input) {
        return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
    }
    
    $('.def-txt-input')
        .on('keyup paste', handleCharacter)
        .on('keydown', handleBackspace);
    

    I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

提交回复
热议问题