0%

Auto-Focus Next Input in Mini Program Verification Code

At first, I thought that if I needed six verification code boxes, I should simply create six <input> elements.

However, after implementing it, I ran into various issues:

  • The cursor didn’t smoothly jump to the next input box
  • The keyboard would suddenly disappear
  • The overall typing experience felt clunky and not smooth

The correct approach is actually to use only one real input field, and simulate multiple input boxes through styling (spacing, highlighting, etc.).

Visually it looks like six input boxes, but in reality there is only one <input> element handling the input.


Correct Solution

1
2
3
4
5
6
7
8
9
<view class="w-80 h-100 rad-10 b-a-9 tc f-50" v-for="(item,index) in 6">
<input
class="w-80 h-100"
maxlength="1"
type="text"
@input="inputListener(index)"
:focus="focus && (focusIndex == index)"
/>
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
data() {
return {
focus: true,
code: ['', '', '', '', '', ''], // Stores the verification code digits
focusIndex: 0 // Index of the input that should receive focus
}
},
methods: {
// Triggered when input changes
inputListener(index) {
if (this.focusIndex !== index) {
this.focusIndex = index
}

if (index < 6) {
this.focus = true
this.focusIndex = index + 1
} else {
this.focus = false
}
}
}

Complete Version

You can refer to the full implementation here:

https://blog.csdn.net/u011423258/article/details/106683068?spm=1001.2014.3001.5506

-------------本文结束感谢您的阅读-------------