Michael Code
Michael Code

Reputation: 33

Insert hyphen automatically after every 3 characters in a TextBox input-mask

I would like to know how to mask text box to automatically take hyphen after every 3 character.

like ABC-DEF-DBC-HXM-.......so on

I am using jquery.inputmask

Upvotes: 0

Views: 1281

Answers (1)

Varun
Varun

Reputation: 1946

I do not know much of the "inputmask" plugin.

I just tried something to solve it. I haven't tested it yet, but let me know if this is working for you:

var z = 0;
$("#d1").on('keyup', function (event) {
    console.log(event.keyCode);
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90)) {
        var t = $(this).val();
        console.log(t.length);
        console.log("VALUE OF Z" + z);
        if (t.length == 3 || (((t.length) - z) % 3) == 0) {
            t = t + "-";
            z++;
        }

        $(this).val(t);
    } else {
        event.preventDefault();
        var v = $(this).val().trim();
        v = v.substring(0, v.length - 1);
        $(this).val(v);
    }
});

and your HTML will be

<input type="text" id="d1" SIZE="200"/>

Upvotes: 0

Related Questions