Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequential number input boxes with auto focus for pure java script
<html>
<body>
<input id="number-1" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<input id="number-2" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<input id="number-3" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<input id="number-4" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<input id="number-5" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<input id="number-6" type="text" maxlength="1" onkeypress="goToNext(this, event)" onkeydown="goToPrev(this, event)" />
<script>
function goToNext(sender, event) {
id = sender.id.split('-')[0];
seq = Number(sender.id.split('-')[1]);
seq += 1;
if (seq > 6) {
return;
}
document.getElementById(id + '-' + seq).focus();
}
function goToPrev(sender, event) {
id = sender.id.split('-')[0];
seq = Number(sender.id.split('-')[1]);
seq -= 1;
if (seq < 1) {
return;
}
if(sender.value.length != 0 || event.keyCode !== 8) {
return;
}
document.getElementById(id + '-' + seq).focus();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.