使用jQuery的信用卡输入表 [英] 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
任何非十进制数字都将被忽略,并且用户可以将第5个字符(由连字符表示)输入为数字(成为cc的第5个数字),空格或连字符.
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.
例如以下所有输入都将在输入中显示为1234-1
e.g. all of the following input would be seen in the input as 1234-1
12341
1234 1
1234-1
123whoops4 1
推荐答案
尝试一下:
$('#theInput').blur(function()
{
$(this).val(function(i, v)
{
var v = v.replace(/[^\d]/g, '').match(/.{1,4}/g);
return v ? v.join('-') : '';
});
});
在这里尝试: http://jsfiddle.net/hnbx4/
这是解释:
第一:
v.replace(/[^\d]/g, '')
我们过滤输入内容以仅包含数字.然后:
we filter through the input to contain only numbers. Then:
.match(/.{1,4}/g);
我们将数字字符串分成4位数字的大块.然后:
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.
这篇关于使用jQuery的信用卡输入表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!