I have 5 inputs, everyone of them will wait for a letter. Once one is filled with a letter I have to automatically jump to the next input.
Problem is that, if I capture only keyup
this makes me jump correctly, but doesn't let me to write "quickly".
e.g Let's say I have to write the word 'megan', so I start with m
but if I press e
before I release (keyup) the m
key, then I get weird behaviour.
This is the HTML
<form>
<div class="code-cell"><input id="code-1" tabindex="1" class="code-input" type="text" data-isvalid="false" /></div>
<div class="code-cell"><input id="code-2" tabindex="2" class="code-input" type="text" maxlength="1" data-isvalid="false" /></div>
<div class="code-cell"><input id="code-3" tabindex="3" class="code-input" type="text" maxlength="1" data-isvalid="false" /></div>
<div class="code-cell"><input id="code-4" tabindex="4" class="code-input" type="text" maxlength="1" data-isvalid="false" /></div>
<div class="code-cell"><input id="code-5" tabindex="5" class="code-input" type="text" maxlength="1" data-isvalid="false" /></div>
</form>
The javascript (capturing the keydown
event)
var goTo = function (curIndex, nextIndex, e) {
// Backwards
if ((curIndex > codeMinLength) && (nextIndex < curIndex)) {
if (nextIndex < 5 && $('#code-' + curIndex).val() === '') {
$('#code-' + nextIndex).focus();
}
$('#code-' + curIndex).val('');
}
// Foreward
if ((curIndex < codeMaxLength) && (nextIndex > curIndex)) {
if ($('#code-' + curIndex).val().trim().length > 0) {
// Force the keyup of the previous pressed key not yet released
$('#code-' + nextIndex).focus();
}
}
};
var eventToCapture = (window._PFN.isMobile) ? 'keyup' : 'keydown';
$('.code-input').on(eventToCapture, function (e) {
var $input = $(e.target);
var keyCode = e.keyCode || e.which;
curIndex = parseInt($input.attr('tabindex'));
nextIndex = null;
if(e.keyCode === 13) {
return validateCode();
}
if (keyCode === 8) { // Backspace
nextIndex = curIndex - 1;
} else {
nextIndex = curIndex + 1;
}
//$('.code-input').on('keyup', function(e){
goTo(curIndex, nextIndex, e);
//});
});
Doing this in keydown
let me write quickly, but doesn't let me jump smoothly to the next input.
I was wondering if I could force any keyup when a keydown is detected.