Code number form

by maxell4o

HTML

<form action="">
    <input type="text" maxlength="1" placeholder="-" required>
    <input type="text" maxlength="1" placeholder="-" required>
    <input type="text" maxlength="1" placeholder="-" required> -
    <input type="text" maxlength="1" placeholder="-" required>
    <input type="text" maxlength="1" placeholder="-" required>
    <input type="text" maxlength="1" placeholder="-" required>
    <button type="submit">sent</button>
</form>

SCSS

input{
	width: 50px;
	height: 50px;
	text-align: center;
	font-size: 30px;
}

JavaScript

$('input').on('keydown input', e => {
    if (e.type == 'keydown') {
        if (!(new RegExp(/\d+/)).test(e.key)) {
            if (e.keyCode != 8 && e.keyCode != 9) {
                e.preventDefault();
            }
        } else {
            e.target.value = null;
        }

        if (e.keyCode == 8 && !e.target.value && e.target.previousElementSibling &&
            e.target.previousElementSibling.tagName == 'INPUT') {
            setTimeout(() => e.target.previousElementSibling.focus())
        }

        /* Go to previous INPUT with left arrow key*/
        if (e.keyCode == 37 && e.target.previousElementSibling &&
            e.target.previousElementSibling.tagName == 'INPUT') {
            e.target.previousElementSibling.focus();
        }

        /* Go to next INPUT with right arrow key*/
        if (e.keyCode == 39 && e.target.nextElementSibling &&
            e.target.nextElementSibling.tagName == 'INPUT') {
            e.target.nextElementSibling.focus();
        }
    }
    if (e.type == 'input') {
        if (e.target.value && e.target.nextElementSibling &&
            e.target.nextElementSibling.tagName == 'INPUT') {
            e.target.nextElementSibling.focus();
        }
    }
});