日常JS汇总-金额自动添加分隔符

function currencyFormat(input,e){
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var aux = aux2 = '';
var strCheck = '0123456789';
var re=/(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
var whichCode = (window.Event) ? e.which : e.keyCode;//获取当前用户输入的键盘
//alert("键盘输入值="+whichCode);
if (whichCode == 13) return true; // 如果用户输入正确返回
key = String.fromCharCode(whichCode); // 获得用户输入的键盘值
len = input.value.length; //获得当前文本框字符串长度
//alert("len="+len);
if (len == 0 && strCheck.indexOf(key) != -1) {
return true; //如果文本框当前为空,输入数字,返回当前数字
}
if(len <= 2 ){
if (strCheck.indexOf(key) != -1 || whichCode == 46){//判断输入金额是否为"0123456789."

if (whichCode == 46){//判断输入是否是"."
if(input.value.indexOf('.') != -1){//判断文本框字符串是否已经存在"."
return false;
}else{
return true;
}
}else{//如果不是"."输入数字字符生效
return true;
}
}else{ //不是,输入键盘无效
return false;
}
}
if(len > 2){//当前文本框字符串长度大于3时
aux = input.value;
// alert(aux);
if (aux.indexOf('.') != -1){//判断是否带小数的金额
var strInput = aux.split('.');
if (strInput[0].length > 3){
if(strInput[0].indexOf(',') != -1){
strInput[0] = strInput[0].replace(/\,/g,"");
}
strInput[0] = strInput[0].replace(re,"$1,");
}
if (strInput[1].length <2){
if (strCheck.indexOf(key) != -1){
strInput[1] += key;
}else{
return false;
}
}
input.value = strInput[0]+"."+strInput[1];
}else{
if (strCheck.indexOf(key) != -1 || whichCode == 46){
if(aux.indexOf(',') != -1){
aux = aux.replace(/\,/g,"");
}
aux +=key;
aux = aux.replace(re,"$1,");
input.value = aux;
}else{
return false;
}
}
return false;
}
}
</script>

测试语句:
<input name = 'a' type='text' onKeyPress="return(currencyFormat(this,event))" onChange="">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值