HTML page code example:
<
div
class
=
"wrap"
>
<
input
type
=
"text"
id
=
"bankCard"
placeholder
=
"输入银行卡号"
>
</
div
>
<
div
class
=
"wrap"
>
<
input
type
=
"text"
id
=
"moneyNum"
placeholder
=
"输入金额"
>
</
div
>
Format the bank card number (each four-bit sub-group)
$(
"#bankCard"
).on(
"keyup"
, formatBC);
function
formatBC(e){
$(
this
).attr(
"data-oral"
, $(
this
).val().replace(/\ +/g,
""
));
//$("#bankCard").attr("data-oral")获取未格式化的卡号
var
self = $.trim(e.target.value);
var
temp =
this
.value.replace(/\D/g,
‘‘
).replace(/(....)(?=.)/g,
‘$1 ‘
);
if
(self.length > 22){
this
.value = self.substr(0, 22);
return
this
.value;
}
if
(temp !=
this
.value){
this
.value = temp;
}
}
formatted amount input (xxx,xxx.xx)
$(
"#moneyNum"
).on(
"keyup"
, formatMN);
$(
"#moneyNum"
).on({
focus:
function
(){
$(
this
).attr(
"data-fmt"
,$(
this
).val());
//将当前值存入自定义属性
},
blur:
function
(){
var
oldVal=$(
this
).attr(
"data-fmt"
);
//获取原值
var
newVal=$(
this
).val();
//获取当前值
if
(oldVal!=newVal) {
if
(newVal ==
""
|| isNaN(newVal)){
this
.value =
""
;
return
this
.value;
}
var
s =
this
.value;
var
temp;
if
(/.+(\..*\.|\-).*/.test(s)){
return
;
}
s = parseFloat((s +
""
).replace(/[^\d\.\-]/g,
""
)).toFixed(2) +
""
;
var
l = s.split(
"."
)[0].split(
""
).reverse(),
r = s.split(
"."
)[1];
t =
""
;
for
(i = 0; i < l.length; i ++ ) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length && (l[i+1]!=
‘-‘
)?
","
:
""
);
}
temp = t.split(
""
).reverse().join(
""
) +
"."
+ r;
this
.value = temp;
return
this
.value;
}
}
});
function
formatMN(e){
this
.value =
this
.value.replace(/[^\d\.\-]/g,
""
);
$(
this
).attr(
"data-oral"
, parseFloat(e.target.value.replace(/[^\d\.-]/g,
""
)));
//$("#moneyNum").attr("data-oral")获取未格式化的金额
}
Input box can only enter a pure number, cannot enter other symbols<input type= "text" onkeyup= "Value=value.replace (/[^\d]/g, ')" ng-pattern= "/[^a-za-z]/"/>
Input box can only enter the pure number + formatted input amount with the bank card JS code