How to set focus on next textbox on Enter Key using jQuery

I had already posted about "How to Set focus on First textbox of page using jQuery", but there was a situation where I need to move to next textbox using Enter key. Normally, tab key is used to move to next text box and by default, when Enter key is pressed, the form gets submitted or it calls the default button click event. But it would be a nice feature for end-user to give him ability to move to next textbox using Enter key.

As I always say "Not to worry, when we have jQuery". This can be done with jQuery as well. First see the jQuery code.
$(document).ready(function() {
 $('input:text:first').focus();
    
 $('input:text').bind("keydown", function(e) {
    var n = $("input:text").length;
    if (e.which == 13) 
    { //Enter key
      e.preventDefault(); //Skip default behavior of the enter key
      var nextIndex = $('input:text').index(this) + 1;
      if(nextIndex < n)
        $('input:text')[nextIndex].focus();
      else
      {
        $('input:text')[nextIndex-1].blur();
        $('#btnSubmit').click();
      }
    }
  });

  $('#btnSubmit').click(function() {
     alert('Form Submitted');
  });
});
Explanation:
The document.ready() when gets executed then it first set the focus to the very first textbox of the page using "$('input:text:first').focus();". Read How to Set focus on First textbox of page using jQuery. There is a keydown function which is binded to all the textbox using bind metohd. Read more about bind. If you are using ajax, then don't use bind use live method. Read about live.

Now, the keydown function, first find the total number of textboxes in the page. Read Get total count of textboxes using jQuery.
var n = $("input:text").length;
Then, it check whether entry key is pressed If Yes, then prevent its default behavior. Take the index of next textbox and assign it to nextIndex variable.
var nextIndex = $('input:text').index(this) + 1;
After that it checks whether nextIndex is less than the total count of textbox. If Yes, then it sets the focus to next textbox and if not, then it removes the focus from current textbox and set for "Submit button".
if(nextIndex < n)
   $('input:text')[nextIndex].focus();
else
{
  $('input:text')[nextIndex-1].blur();
  $('#btnSubmit').click();
}
Simple and really cool functionality.
See live Demo and Code.
Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..