OTP UI html javascript
OTP UI
by sunil puvvada
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="codeBox1" name="no1" type="number" min="1" max="1" onkeyup="onKeyUpEvent(1, event)" onfocus="onFocusEvent(1)">
<input id="codeBox2" name="no1" type="number" maxlength="1" onkeyup="onKeyUpEvent(2, event)" onfocus="onFocusEvent(2)">
<input id="codeBox3" name="no1" type="number" maxlength="1" onkeyup="onKeyUpEvent(3, event)" onfocus="onFocusEvent(3)">
<input id="codeBox4" name="no1" type="number" maxlength="1" onkeyup="onKeyUpEvent(4, event)" onfocus="onFocusEvent(4)">
<input id="codeBox5" name="no1" type="number" maxlength="1" onkeyup="onKeyUpEvent(5, event)" onfocus="onFocusEvent(5)">
<input id="codeBox6" name="no1" type="number" maxlength="1" onkeyup="onKeyUpEvent(6, event)" onfocus="onFocusEvent(6)">
JavaScript
$('input[name="no1"]').keypress(function() {
if (this.value.length >= 1) {
return false;
}
});
const verifyingOtp_1 = function() {
const res =
$("#codeBox1").val() +
$("#codeBox2").val() +
$("#codeBox3").val() +
$("#codeBox4").val() +
$("#codeBox5").val() +
$("#codeBox6").val();
const tempValueCal = {
lengthOtpCode: res.length,
otpCode_MMK: res,
phoneNumber_MMK: 12121,
};
return tempValueCal;
};
function getCodeBoxElement(index) {
return document.getElementById('codeBox' + index);
}
function onKeyUpEvent(index, event) {
const eventCode = event.which || event.keyCode;
if (getCodeBoxElement(index).value.length === 1) {
if (index !== 6) {
getCodeBoxElement(index + 1).focus();
} else {
getCodeBoxElement(index).blur();
// Submit code
console.log('submit code ');
console.log(verifyingOtp_1());
}
}
if (eventCode === 8 && index !== 1) {
getCodeBoxElement(index - 1).focus();
}
}
function onFocusEvent(index) {
for (item = 1; item < index; item++) {
const currentElement = getCodeBoxElement(item);
if (!currentElement.value) {
currentElement.focus();
break;
}
}
}