Search code examples
javascriptjquerytextbox

In Javascript, how do I automatically move the cursor to the next text box when the current one is full?


Suppose I have two HTML textboxes on my web page:

<input type='text' id='txt1' maxlength='5' />
<input type='text' id='txt2' maxlength='5' />

Each textbox allows the user to type up to five characters. How can I use Javascript with or without jQuery to automatically move the cursor from txt1 to txt2 when the user types five charcters into txt1?


Solution

  • A basic implementation would be like this:

     $('#txt1').keyup(function() {
         if(this.value.length == $(this).attr('maxlength')) {
             $('#txt2').focus();
         }
     });
    

    But there are some usability subtleties to it you may or may not care about. If you find the above to be insufficient, there are many jQuery plugins out there to do this for you.