It's been a year or two since I last dabbled in jQuery and have attempted to write a simple "on key press move to the next element" script. However my first attempt has a lot a repetition. I just know there is a more elegant way to write this, probably using a dictionary of elements or such.

$("#DialFirst").keypress(function () {

    $("#DialSecond").keypress(function () {

    $("#DialThird").keypress(function () {

    $("#DialFourth").keypress(function () {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="DialFirst" name="DialFirst" type="text" value="" />
<input id="DialSecond" name="DialSecond" type="text" value="" />
<input id="DialThird" name="DialThird" type="text" value="" />
<input id="DialFourth" name="DialFourth" type="text" value="" />
<input id="DialFifth" name="DialFifth" type="text" value="" />

Usage: Type in each box, focus should move to the next.


1 Answer 1


The input elements are all siblings of each other, so you can use $.next() to select the next one that appears after the event target. There is no need to name each input individually.

$(':input').keypress(function() {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input placeholder="1">
<input placeholder="2">
<input placeholder="3">
<input placeholder="4">
<input placeholder="5">

  • \$\begingroup\$ Is this working in chrome? I tested and it'ss not working but working in firefox. \$\endgroup\$ Jun 22, 2021 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.