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
?
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.
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.
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.
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With