Javascript 信用卡号格式
我正在尝试创建一个漂亮的信用卡号输入字段,当用户输入信用卡号时,它会自动格式化信用卡号。以下是我所拥有的:Javascript 信用卡号格式,javascript,jquery,coffeescript,Javascript,Jquery,Coffeescript,我正在尝试创建一个漂亮的信用卡号输入字段,当用户输入信用卡号时,它会自动格式化信用卡号。以下是我所拥有的: # Whenever the credit card input changes, update its value. $(".credit-card-number").on "input", -> # retrieve the credit card number creditCardNumber = $(this).val() # remove everythin
# Whenever the credit card input changes, update its value.
$(".credit-card-number").on "input", ->
# retrieve the credit card number
creditCardNumber = $(this).val()
# remove everything that's not a number
creditCardNumber = creditCardNumber.replace(/[^\d]+/g, "")
# ensure the value isn't more than 16 characters long
creditCardNumber = creditCardNumber[0..15]
# break apart the value every four numbers
creditCardNumber = creditCardNumber.match(/.{1,4}/g)
# insert spaces in the value when the value isn't null
creditCardNumber = if creditCardNumber? then creditCardNumber.join(" ") else ""
# set the value
$(this).val(creditCardNumber)
这在以下HTML上非常有效:
<input class="credit-card-number" id="credit_card_number" name="credit_card_number" placeholder="Credit card number" type="text">
但是,如果我将输入的类型设置为
number
,每当我更新该值并且该值包含空格时,Chrome就会将该值更改为空字符串。有什么想法吗?放弃我以前的答案
无法获得空间的原因是jQuery正在对您试图设置的值执行排序验证。数字中不允许有空格,因此它正在清除该值。当你输入一个字母时,同样的事情也会发生
没有任何东西可以阻止您(至少在Chrome中)在
字段中输入字母。它是无效的,如果您提交表单,该字段将包含一个空值(尚未测试该值)。放弃我以前的答案
无法获得空间的原因是jQuery正在对您试图设置的值执行排序验证。数字中不允许有空格,因此它正在清除该值。当你输入一个字母时,同样的事情也会发生
没有任何东西可以阻止您(至少在Chrome中)在
字段中输入字母。它是无效的,如果您提交表单,该字段将包含一个空值(尚未测试该值)。您可以做的另一件事是使用
而不是数字。如果你只想输入数字,我更愿意用它在移动设备上安装数字键盘
信用卡号的格式将与tel
配合使用。您可以做的另一件事是使用
而不是number
。如果你只想输入数字,我更愿意用它在移动设备上安装数字键盘
信用卡号的格式设置将使用tel
是的,如果您希望值中有空格,请不要使用number
输入。为什么需要将类型设置为number
,而不是text
?您可以使用regex检查您的号码格式。我个人从不相信浏览器的数字,因为本地化问题。我想使用数字输入的原因是因为输入中包含的值是数字。它是要使用的语义正确的输入。另外,在移动设备上,它将显示一个数字键盘,而不是一个完整的键盘。是的,如果您希望值中有空格,就不要使用数字
输入。为什么需要将类型设置为数字
,而不是文本
?您可以使用regex检查数字格式。我个人从不相信浏览器的数字,因为本地化问题。我想使用数字输入的原因是因为输入中包含的值是数字。它是要使用的语义正确的输入。另外,在移动设备上,它将显示一个数字键盘,而不是一个完整的键盘。太棒了。至少现在我知道问题出在哪里了。也许我该提交我的第一个jQuery补丁了。:)谢谢你的帮助,太棒了。至少现在我知道问题出在哪里了。也许我该提交我的第一个jQuery补丁了。:)谢谢你的帮助。