TK. TK. - 10 months ago 119
Javascript Question

Moving a focus when the input text field reaches a max length

I do have a credit card number form. The number is divided into four parts just as on a real credit card.

I want to add a JavaScript taste to the form where when a user types four letters in a field, the focus automatically goes to the next tag. But not in the last tag. By doing this, a user doesn't have to type "tab" key to move a focus.

It is okay to add some extra class, id or name in the tags.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src=""></script>
<script type="text/javascript" charset="utf-8">
$(function() {
// some code goes here.

<form action="post.php" method="post" accept-charset="utf-8">
<input type="text" value="" id="first" size="4" maxlength="4"/> -
<input type="text" value="" id="second" size="4" maxlength="4"/> -
<input type="text" value="" id="third" size="4" maxlength="4"/> -
<input type="text" value="" id="fourth" size="4" maxlength="4"/>
<p><input type="submit" value="Send Credit Card"></p>

Answer Source

I haven't used this tool before, but it does what you want. You could just look at it's source to get some ideas:

This Plugin on GitHub

For your situation, you would add this code:

<script type="text/javascript" src="jquery.autotab.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('#first').autotab({ target: '#second', format: 'numeric' });
    $('#second').autotab({ target: '#third', format: 'numeric', previous: '#first' });
    $('#third').autotab({ previous: '#second', format: 'numeric' });