Google trends Public Holidays Coupon Code Code Compiler

Move Cursor to next text Field pressing Enter


Dec 25, 2018

In this article, you'll know how to cursor moves to another text-field pressing Enter. We have multiple text fields in the form and we want when we enters data in one text field and press enter that the cursor moves to another text-field which is next to current text field.

HTML Code:


<input class="txtfield">
<input class="txtfield">
<input class="txtfield">
<input class="txtfield">
<input class="txtfield">
<input class="txtfield">
<input class="txtfield">

JavaScript Code:


$(".txtfield").keyup(function (event) {
    if (event.keyCode == 13) {
        txtbox = $("input.txtfield");       
        currenttxtfieldNumber = txtbox.index(this);
        if (txtbox[currenttxtfieldNumber + 1] != null) {
            nextBox = txtbox[currenttxtfieldNumber + 1];
            nextBox.focus();
            nextBox.select();
        }
        event.preventDefault();
        return false;
    }
});

ENTER doesn't trigger keypress in all browsers, used keyup instead. Also attached eventlistener to each input instead of a wrapper.
Your code with event delegation will also work with a slight change:


currentBoxNumber = textboxes.index(event.target);

this on above sentence would refer to the wrapper instead of the input, event.target refers to the actual element which fired the event.

Copyright 2024. All rights are reserved