How can I focus the next input once the previous input has reached its maxlength value?
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.
jsFiddle: http://jsfiddle.net/4m5fg/1/
I must stress that I do not want to use a plugin, as I'd much rather learn the logic behind this, than use something that already exists. Thanks for understanding.
Updated btevfik code, Onkeyup or onkeydown will create issue on tab navigation. It will be tough to edit or change the text inside the input box as it will be limited to maxlength. So we can use oninput event to achieve the task.
DEMO
HTML
Javascript
CSS
if you are going to have many fields you can do something like this.
basically on
keyup
get the length of the input and then compare it to the maxlength, if matches, thenfocus
onto the next input field.http://jsfiddle.net/btevfik/DVxDA/
No jQuery used and is a very clean implementation:
http://jsfiddle.net/4m5fg/5/
..
If you are adding input text fields dynamically then you can try this.
This will re-inject the script into the DOM and works Perfectly.
You can watch for input in the fields and test its value:
Working demo.
The
setTimeout
is there to ensure the code will only run after the input is completed and the value updated. Bindinginput
ensures most types of input will trigger the event, including key presses, copy/paste (even from mouse) and drag & drop (though in this case, the latter won't work, since the focus was on the draggable, not the droppable).Note: on some older browsers, you might also need to bind
propertychange
.To do that, you might need to remove the
maxlength
attribute using JavaScript (to be able to capture the full input), and implement that functionality yourself. I made a small example, relevant parts below:This removes the attribute, but saves it in
data
, so you can access it later.Here the max length logic is reintroduced in JavaScript, as well as getting the "discarded" part and using it in a recursive call to
spill
. If there's no next element, the call todata
will returnundefined
and the loop will stop, so the input will be truncated in the last field.Verified Answer have one issue which focus previous field if previous field have valid length
I have Modified Above Answer to fix complete length of previous tag