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 u
As others have urged, don’t do this. Users are not going to be able to anticipate that you’ll auto-tab them, and this will drive them nuts. Have you thought about users who copy and paste their credit card? What is the benefit of using four fields anyway?
Also, not all credit cards divide their numbers into four sets of four. American Express divides them into three groups of numbers, for example. Dynamically adding and removing text fields is asking for trouble in this case.
Instead, use your Javascript to automatically insert the spaces where they belong, advancing the cursor, not the focus. The first digit in the number indicates the type of credit card (5 is Mastercard, 4 is Visa, 3 is American Express…), so you can read this to decide where to add the spaces. Scrub the spaces out of the string when you post it. This approach will save you and your users a lot of pain.
A very simple solution could go like this:
<script type="text/javascript">
function input_onchange(me){
if (me.value.length != me.maxlength){
return;
}
var i;
var elements = me.form.elements;
for (i=0, numElements=elements.length; i<numElements; i++) {
if (elements[i]==me){
break;
}
}
elements[i+1].focus();
}
</script>
<form action="post.php" method="post" accept-charset="utf-8">
<input type="text" value="" id="first" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="second" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="third" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="fourth" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<p><input type="submit" value="Send Credit Card"></p>
</form>