Reputation: 1836
I'm working on a script for our client's project that autotabs you onto the next input field when you've hit the maximum character count for a particular input. For some reason the input value is returning one less than it should be, and therefore tabs to the 'next' input when an extra character is entered above the 'threshold'.
Here's my script to watch the inputs value - ofc, if there is a better way please advise :) -
var watchLength = function (watch) {
watch.onkeypress = function () {
var nextInput = getNextSibling(this);
console.log(this.getAttribute('data-autotab-length'));
console.log(this.value.length);
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
}
};
};
And a jsFiddle to the working input. The first input is limited to '2' characters, but when you type in 3 it jumps to the next input. I think this is something to do with the keypress/keydown event not reading the initial value, but I'm at a loss of how to fix it. Any help really appreciated.
I'm logging the results in the Console:
Upvotes: 4
Views: 2531
Reputation: 56501
if (this.value.length == this.getAttribute('data-autotab-length')) {
nextInput.focus();
console.log('Limit reached here');
return false; // this is prevent the third value being entered
}
Upvotes: 0
Reputation: 21233
Use onkeyup
instead onkeypress
onkeyup
gets fired after field gets updated
Upvotes: 0
Reputation: 1650
Yes it will return one less, simply use +1 on the length check. This is beacuse onkeypress
event is executed before the field is updated, which means using e.preventDefault()
the letter will not appear in the field. You could use onkeyup
otherwise.
Upvotes: 0
Reputation: 235982
The Problem is, that onkeypress
will fire before you want it to. You can simply replace onkeypress
by onkeyup
, that way you make sure that the <input>
elements value
is set correctly the time you check it.
See: http://jsfiddle.net/qdnCZ/1/
Upvotes: 4