gpt4 book ai didi

javascript - 转到 maxLength 的下一个输入字段?

转载 作者:行者123 更新时间:2023-12-05 03:45:15 25 4
gpt4 key购买 nike

我在 Vue 中有一个表单,由于电话号码输入的样式原因,它有一些组合输入。

我的问题是用户必须点击 Tab 键才能转到电话号码的下一个输入字段。

有没有办法检查当前和输入的最大长度,并在满足时转到下一个输入?

<div class="combined-input combined-input--phone" :class="{'error--input': phoneInvalid('patientInformation')}">
<div class="open-parenthesis"></div>

<input type="text" id="phoneArea" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.area.$model">

<div class="close-parenthesis"></div>

<input type="text" id="phoneA" maxlength="3" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.a.$model">

<div class="dash"></div>

<input type="text" id="phoneB" maxlength="4" @blur="$v.formData.patientInformation.phone.$touch()" v-model.trim="$v.formData.patientInformation.phone.b.$model">
</div>

最佳答案

很确定这在用户体验方面不被推荐,但这里有一个关于如何实现它的例子:https://codesandbox.io/s/move-to-next-input-on-condition-103b5?file=/src/App.vue

有用代码的主要部分是

focusNextOncePopulated(event, max) {
if (event.target.value.length === max) {
const nextElement = this.$refs?.[`input-${Number(event.target.dataset.index) +1}`]
if (nextElement) nextElement.focus()
}
},

说明:每次输入一个字符时,您都会检查该字段的长度是否达到了您在特定输入上设置的最大值。如果是,并且有与 sibling 相似的输入,则关注它。
添加 debounce在性能方面,几毫秒也不错。

编辑:为了防止在 DOM 中尝试找到正确的下一个 input 时出现任何问题,我们在每个输入上设置了一些 refs(在 Vue 中推荐的选择一些 DOM 元素的方式)。然后,当我们达到 max 时,我们将当前的输入 data-index 增加 1,这使我们能够转到下一个输入。

PS: ?. 语法是optional chaining , 它可以防止丑陋的代码,并允许在达到 max 后没有下一个 input 时避免错误。

PS:不确定是否有办法直接获取元素的 $refs@input 事件,但如果有,我没有找到了解如何去做。

关于javascript - 转到 maxLength 的下一个输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65903746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com