I’m trying to make an aesthetically pleasing credit card input form on my website.
I’d like a the form to display in the following format:
1234-1234-1234-1234
Any non decimal number would be ignored, and the 5th character (represented by the hyphen), could be entered by the user as a number (becomes the 5th number of the cc), a space, or a hyphen.
e.g. all of the following input would be seen in the input as 1234-1
12341
1234 1
1234-1
123whoops4 1
Try this:
Try it here: http://jsfiddle.net/hnbx4/
Here’s the explanation:
First:
we filter through the input to contain only numbers. Then:
we split the string of numbers into 4-digit chunks. Then:
if an array, we combine the array by inserting a dash between the chunks. Otherwise we just set it to an empty string.