Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Credit Card Input Form Using jQuery

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
like image 600
Tyler DeWitt Avatar asked Dec 27 '22 04:12

Tyler DeWitt


1 Answers

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.

like image 86
Joseph Silber Avatar answered Jan 06 '23 10:01

Joseph Silber