1
\$\begingroup\$

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").focus();
    });

    $("#DialSecond").keypress(function () {
        $("#DialThird").focus();
    });

    $("#DialThird").keypress(function () {
        $("#DialFourth").focus();
    });

    $("#DialFourth").keypress(function () {
        $("#DialFifth").focus();
    });
<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.

\$\endgroup\$
5
\$\begingroup\$

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() {
    $(this).next(':input').focus();
});
<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">

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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