Move Cursor to next text Field pressing Enter

Try this , as soon as you press it will move to next input field in the form, and when it reaches submit button it will submit the form

            <html>
     <head>
       <title></title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script type='text/javascript'>
        $(document).ready(function(){
            $('#myForm input').keydown(function(e){
             if(e.keyCode==13){       

                if($(':input:eq(' + ($(':input').index(this) + 1) + ')').attr('type')=='submit'){// check for submit button and submit form on enter press
                 return true;
                }

                $(':input:eq(' + ($(':input').index(this) + 1) + ')').focus();

               return false;
             }

            });
        });
        </script>
     </head>
     <body>
      <form action="" id="myForm"  >
        <input type='text'  name='firstField'>
            <input type='text' name='secondField'>

            <input type='text' name='secondField'>

            <input type='text' name='secondField'>
        <input type='submit'>
      </form>
     </body>
    </html>

$("input").keypress(function(e) {
  if (e.which == 13) {
    var index = $("input[type='text']").index(this);
    $("input[type='text']").eq(index + 1).focus();
    e.preventDefault();
  }
});

It worked perfectly for me and supports almost every jquery versions!


This should work:

$(".username").keyup(function (event) {
    if (event.keyCode == 13) {
        textboxes = $("input.username");
        currentBoxNumber = textboxes.index(this);
        if (textboxes[currentBoxNumber + 1] != null) {
            nextBox = textboxes[currentBoxNumber + 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.

A live demo at jsFiddle.

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.

A live demo at jsFiddle.