In Javascript, how do I automatically move the cursor to the next text box when the current one is full?
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.