Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 364
Vivian River Avatar asked Dec 14 '10 21:12

Vivian River


People also ask

How to move cursor automatically in JavaScript?

To do this, we use document. elementFromPoint(x+px, y+py) in which we pass the position of image cursor. This will gives us the object of the element, the image cursor is on. After obtaining the required object, we can invoke the object.

How do I move a cursor from one TextBox to another?

Use the TextBox. Focus() method on the next TextBox. Use the first TextBox's TextBox. TextChanged event to test if focus should be changed and to call the Focus method on the next TextBox.


3 Answers

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.

like image 142
Paolo Bergantino Avatar answered Nov 15 '22 14:11

Paolo Bergantino


It's called autotabbing, and there are many plugins that already exist for jquery that do this. Just google it.

If you want to know how to do it, then you bind an onkeyup event to inputs. Every time a key is released, make sure its not a functional key such as "Tab" (You should allow the user to "Shift+Tab" or "Tab" to the input without it then autotabbing to the next field.)

Then, if the input value's length exceeds the input's maxlength attribute, set the focus on the next input (in jQuery, $currentInput.next('input').focus().

like image 26
simshaun Avatar answered Nov 15 '22 16:11

simshaun


None of these solutions work in straight Javascript... this snippet is a start:

document.getElementById('txt1').onkeydown = function() {
  if (this.value.length == this.maxLength)
   document.getElementById('txt2').focus();
}

But once you have entered the number, you can't go back and edit it, because as soon as you hit delete, it jumps back to txt2.

The only thing to change is make it onkeyup instead. :D

jQuery is overkill and lazy programming for the vast majority of things it is used on, and this is a great example. Unless you are already using it on the page, it is an awful lot of overhead for such a tiny task.

like image 40
Eric Sebasta Avatar answered Nov 15 '22 14:11

Eric Sebasta