aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/bootstrap/tfa.js
blob: ffac875d506212dd7c501b34afa9a5f0208fea8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
$(document).on('keyup', '.tfa-code-input input', function (event) {
    this.value = this.value.replace(/^D/g, '');
    if (event.keyCode === 8) {
        $(this).prev('input').focus();
        if (this.value.length === 0) {
            $(this).prev('input').val('');
        }
    } else if (event.keyCode === 46) {
        $(this).nextAll('input:not(:hidden)').each(function () {
            $(this).prev().val(this.value);
            this.value = '';
        });
    } else if (event.keyCode === 37) {
        $(this).prev('input').focus();
    } else if (event.keyCode === 39) {
        $(this).next('input').focus();
    } else if (event.key >= '0' && event.key <= '9') {
        this.value = event.key;
        $(this).next('input').focus();
    } else if (event.keyCode === 36) {
        $(this).parent().find('input:not(:hidden):first').focus();
    }
}).on('keydown', '.tfa-code-input', function (event) {
    if (event.key >= '0' && event.key <= '9') {
        this.value = '';
        event.preventDefault();
    }
}).on('paste', '.tfa-code-input input', function () {
    this.value = '';
    $(this).one('input', function () {
        const pastedValue = this.value.trim();
        if (!pastedValue.match(/^\d{6}$/)) {
            return;
        }

        const container = $(this).closest('.tfa-code-input');
        for (let i = 0; i < 6; i += 1) {
            $(`input:eq(${i})`, container).val(pastedValue.substr(i, 1))
        }
        $('input:last', container).focus();
    });
});