1+ function updateInput ( ) {
2+ let inputValue = Array . from ( inputs ) . reduce ( function ( otp , input ) {
3+ otp += ( input . value . length ) ? input . value : ' ' ;
4+ return otp ;
5+ } , "" ) ;
6+ document . querySelector ( "input[name=otp]" ) . value = inputValue ;
7+ }
8+
9+ window . onload = ( ) => {
10+ const inputs = document . querySelectorAll ( "#otp-input input" ) ;
11+
12+ for ( let i = 0 ; i < inputs . length ; i ++ ) {
13+ const input = inputs [ i ] ;
14+
15+ input . addEventListener ( "input" , function ( ) {
16+ // handling normal input
17+ if ( input . value . length == 1 && i + 1 < inputs . length ) {
18+ inputs [ i + 1 ] . focus ( ) ;
19+ }
20+
21+ // if a value is pasted, put each character to each of the next input
22+ if ( input . value . length > 1 ) {
23+ // sanities input
24+ if ( isNaN ( input . value ) ) {
25+ input . value = "" ;
26+ updateInput ( ) ;
27+ return ;
28+ }
29+
30+ // split characters to array
31+ const chars = input . value . split ( '' ) ;
32+
33+ for ( let pos = 0 ; pos < chars . length ; pos ++ ) {
34+ // if length exceeded the number of inputs, stop
35+ if ( pos + i >= inputs . length ) break ;
36+
37+ // paste value
38+ let targetInput = inputs [ pos + i ] ;
39+ targetInput . value = chars [ pos ] ;
40+ }
41+
42+ // focus the input next to the last pasted character
43+ let focus_index = Math . min ( inputs . length - 1 , i + chars . length ) ;
44+ inputs [ focus_index ] . focus ( ) ;
45+ }
46+ updateInput ( ) ;
47+ } ) ;
48+
49+ input . addEventListener ( "keydown" , function ( e ) {
50+ // backspace button
51+ if ( e . keyCode == 8 && input . value == '' && i != 0 ) {
52+ // shift next values towards the left
53+ for ( let pos = i ; pos < inputs . length - 1 ; pos ++ ) {
54+ inputs [ pos ] . value = inputs [ pos + 1 ] . value ;
55+ }
56+
57+ // clear previous box and focus on it
58+ inputs [ i - 1 ] . value = '' ;
59+ inputs [ i - 1 ] . focus ( ) ;
60+ updateInput ( ) ;
61+ return ;
62+ }
63+
64+ // delete button
65+ if ( e . keyCode == 46 && i != inputs . length - 1 ) {
66+ // shift next values towards the left
67+ for ( let pos = i ; pos < inputs . length - 1 ; pos ++ ) {
68+ inputs [ pos ] . value = inputs [ pos + 1 ] . value ;
69+ }
70+
71+ // clear the last box
72+ inputs [ inputs . length - 1 ] . value = '' ;
73+ input . select ( ) ;
74+ e . preventDefault ( ) ;
75+ updateInput ( ) ;
76+ return ;
77+ }
78+
79+ // left button
80+ if ( e . keyCode == 37 ) {
81+ if ( i > 0 ) {
82+ e . preventDefault ( ) ;
83+ inputs [ i - 1 ] . focus ( ) ;
84+ inputs [ i - 1 ] . select ( ) ;
85+ }
86+ return ;
87+ }
88+
89+ // right button
90+ if ( e . keyCode == 39 ) {
91+ if ( i + 1 < inputs . length ) {
92+ e . preventDefault ( ) ;
93+ inputs [ i + 1 ] . focus ( ) ;
94+ inputs [ i + 1 ] . select ( ) ;
95+ }
96+ return ;
97+ }
98+ } ) ;
99+ }
100+ } ;
0 commit comments