JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" class="def-txt-input" name="chars[1]">
<input type="text" class="def-txt-input" name="chars[2]">
<input type="text" class="def-txt-input" name="chars[3]">
JavaScript
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,3),
rest = $input.val().slice(3),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (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 = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup', handleCharacter)
.on('keydown', handleBackspace);
$('.def-txt-input').on('paste', function(){
setTimeout( function() {
$('.def-txt-input').trigger('keydown')
alert('test')
}, 100);
})