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:
$('#theInput').blur(function()
{
$(this).val(function(i, v)
{
var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
return v ? v.join('-') : '';
});
});
Try it here: http://jsfiddle.net/hnbx4/
Here's the explanation:
First:
v.replace(/[^\d]/g, '')
we filter through the input to contain only numbers. Then:
.match(/.{1,4}/g);
we split the string of numbers into 4-digit chunks. Then:
return v ? v.join('-') : '';
if an array, we combine the array by inserting a dash between the chunks. Otherwise we just set it to an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With