Search code examples
javascriptjqueryfocusonkeydownbackspace

how to focus back when textbox is empty


I would like to switch back to the previous textbox when current textbox is empty.

I can go next textbox when current textbox is filled but i can not go back when i delete characters (length == 0) in to the textbox.

Here is my textboxes:

<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;}}">

I can go (on filling) like:

txt_1 > txt_2 > txt_3

I can't go back (on deletion) like:

txt_3 > txt_2 > txt_1

Solution

  • To have the textbox value when you get to the event, you should use keyup event instead of keydown.and it should work for you, however I have suggested another solution no repeating the code for each element:

    $('.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" />