JSFiddle - React, Tailwind, and code Playground
by LosHantos
HTML
<input type="text" name="d1" class="verification-code-input">
<input type="text" name="d2" class="verification-code-input">
<input type="text" name="d3" class="verification-code-input">
<input type="text" name="d4" class="verification-code-input">
<input type="text" name="d5" class="verification-code-input">
<input type="text" name="d6" class="verification-code-input">
JavaScript
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.verification-code-input[name="d'+ (index + 1) +'"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.verification-code-input[name="d'+ (index - 1) +'"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split([])[1], 10);
}
$('.verification-code-input')
.on('keyup', handleCharacter)
.on('keydown', handleBackspace);