Auto advance input fields (multi-part serial numbe

2019-07-29 17:08发布

问题:

I'm trying to build a 4-part serial number input that auto-advances for each chunk of the serial number.

e.g. 1-384-3884-39

Also, how would I add the strings together into one string on submit?

回答1:

i do a fiddle for you http://jsfiddle.net/fLz4LL9g/3/

Form:

<form>
    <input id="i1" class="i" type="number" value="">-
    <input id="i2" class="i" type="number">-
    <input id="i3" class="i" type="number">-
    <input id="i4" class="i" type="number">
</form>

Code:

var digitsPerBox = 4;

/// EACH INPUT
$(".i").on("input",function(e) {

    if (e.target.value.length == digitsPerBox) {
        var t = $( e.target );
        if (t.attr("id") == "i4") {
            /// SUBMIT HERE
            var txt = $("#i1").val() + "-" + $("#i2").val() + "-" + $("#i3").val() + "-" + $("#i4").val();
            alert(txt);
        } else {
            /// AUTO FOCUS NEXT BOX
            t.next().focus();
       }
    }
    /// LIMIT DIGITS PER BOX
    if (e.target.value.length > digitsPerBox) {
        e.target.value = e.target.value.substr(0,digitsPerBox);
    }


///// ONLY NUMBER ALLOWED    
}).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&                 (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
});


回答2:

I found a plugin... but would still like to learn the simplest way to do this.

http://www.jqueryscript.net/form/jQuery-Plugin-For-Auto-Tab-Form-Fields-autotab.html



回答3:

If i understand you correctly, I think you could use this function:

Working Demo: http://jsfiddle.net/kfbjy8fr/1/

function getResult() {

    var HTMLinsert = "",
        values = $(document).find('input');


    $.each( values, function( index, element) {

        HTMLinsert += element.value

        if (index !== values.length -1 ) {

            HTMLinsert += '-'
        }


    })

    return HTMLinsert;


}

var checkForTab = function() {

    if ( $(this).prop('maxlength') === $(this).val().length ) {

        $(this).closest('input').next().focus();

    }
}