[英]Credit card number format
I'm trying to create a nifty credit card number input field that automatically formats a credit card number as a user types it in. Here's what I have: 我正在尝试创建一个漂亮的信用卡号输入字段,该字段会在用户输入时自动格式化信用卡号。这是我所拥有的:
# 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)
This works perfectly on the following HTML: 这在以下HTML上非常有效:
<input class="credit-card-number" id="credit_card_number" name="credit_card_number" placeholder="Credit card number" type="text">
However, if I set the input's type to number
, whenever I update the value and the value contains a space, Chrome changes the value to the empty string. 但是,如果我将输入的类型设置为
number
,则每当我更新该值并且该值包含空格时,Chrome都会将该值更改为空字符串。 Any ideas? 有任何想法吗?
Another thing you can do is use <input type="tel" />
instead of number
. 您可以做的另一件事是使用
<input type="tel" />
代替number
。 I prefer to use that anyway for getting a numeric keyboard on mobile devices if you only want to input digits. 如果您只想输入数字,无论如何我还是喜欢使用它在移动设备上安装数字键盘。
The formatting of the credit card number will work with tel
. 信用卡号的格式将与
tel
。
Scrap my previous answer. 取消我以前的答案。
The reason that you can't have the space is because jQuery is performing a validation of sorts on the value you are trying to set. 您没有空间的原因是因为jQuery对您要设置的值执行了排序验证。 Space is not allowed in a number, and so it's clearing the value.
数字中不允许有空格,因此清除了值。 The exact same thing happens when you enter a letter.
当您输入字母时,会发生完全相同的事情。
There is nothing stopping you (at least in Chrome) from entering letters into a <input type="number">
field. 没有什么能阻止您(至少在Chrome中)在
<input type="number">
字段中输入字母。 It's just not valid and AFAIK if you submit the form, that field will contain an empty value (haven't tested this). 这只是无效的,如果您提交表单,则AFAIK无效,该字段将包含一个空值(尚未对此进行测试)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.