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

how to focus back when textbox is empty

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

当当前文本框已填满时,我可以转到下一个文本框,但当我删除文本框中的字符(长度 == 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" />

你可以试试这个

if( $("#txt_1").val() === ''){
        $("#txt_1").focus();
        }