Auto advance input fields (multi-part serial numbe

2019-07-29 16:58发布

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?

3条回答
Rolldiameter
2楼-- · 2019-07-29 17:52

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();

    }
}
查看更多
甜甜的少女心
3楼-- · 2019-07-29 17:58

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

查看更多
做个烂人
4楼-- · 2019-07-29 18:00

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();
        }
});
查看更多
登录 后发表回答