Search code examples
javascriptformsfocuskeycodeonfocus

How can I get focused form element by using JS?


For example

<form>
    <div class="form-control">
       <input type="text" name="username">
    </div>
    <div class="form-control">
       <input type="text" name="password">
    </div>
</form>

when I press tab key when cursor is in input which name is username, How can I get the new focused element that name is password with using JS

When I get the element with this code;

document.addEventListener('keydown', function(evt) 
{

    if (evt.keyCode === 9) {
       console.log(document.activeElement);
    }

});

this returned the input-1 which name is username, but I want to get password input. How can I?


Solution

  • Your event listener is bound to keydown, which means it will trigger before the actual keypress is "complete" (down and then up), so the focus hasn't actually changed when the event handler executes. Change to keyup and the focus will change before your event handler.

    document.addEventListener('keyup', function(evt) 
    {
    
        if (evt.keyCode === 9) {
           console.log(document.activeElement);
        }
    
    });
    <form>
        <div class="form-control">
           <input type="text" name="username">
        </div>
        <div class="form-control">
           <input type="text" name="password">
        </div>
    </form>