gpt4 book ai didi

javascript - 如何在文本框为空时返回焦点

转载 作者:行者123 更新时间:2023-11-30 19:10:07 24 4
gpt4 key购买 nike

当当前文本框为空时,我想切换回上一个文本框。

当当前文本框已填满时,我可以转到下一个文本框,但当我删除文本框中的字符(长度 == 0)时,我无法返回。

这是我的文本框:

<input id="txt_1" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){window.setTimeout(function (){document.getElementById('txt_2').focus();},0);return false;}}">
<input id="txt_2" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){window.setTimeout(function (){document.getElementById('txt_3').focus();},0);return false;}}">
<input id="txt_3" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){return false;}}">

我可以(在填充时)像:

txt_1 > txt_2 > txt_3

我不能返回(删除时),例如:

txt_3 > txt_2 > txt_1

最佳答案

要在到达事件时获得文本框值,您应该使用 keyup 事件而不是 keydown。它应该适合您,但是我建议了另一个解决方案不重复每个元素的代码:

$('.forward').on('keydown', function(e){
if($(this).val().length === 3 && e.which != 8) e.preventDefault();
});
$('.forward').on('keyup', function(e){

if($(this).val().length === 3)
{ if($(this).data('next')) $($(this).data('next')).focus();}
if($(this).val() === '')
{if($(this).data('back')) $($(this).data('back')).focus();}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txt_1" type="number" maxlength="3" data-next="#txt_2" class="forward" />
<input id="txt_2" type="number" maxlength="3" data-next="#txt_3" data-back="#txt_1" class="forward" />
<input id="txt_3" type="number" maxlength="3" data-back="#txt_2" class="forward" />

关于javascript - 如何在文本框为空时返回焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58578320/

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