JavaScript,文本框内强制的美元显示格式

公司某位领导的意见,用户输入数字的时候要将数据字换成美元的显示方法.
有两种思路,一种就是用Ajax,在后台写方法分割字符串.第二种就是直接使用JS来分割字符串.
我实现了只输入纯数字...已经达到了要求,至于想要实现带小数一样边输入边切割,等有需要再议吧.
我用的是JS,事件是文本框的onkeyup 别的实现不了效果.
function AutoFormat()
{
   
 var strNum = this.document.getElementById("money").value;
 var strTemp = 0;
 var newStrNum="";

 for(i=0;i<strNum.length;i++)
 {
   if(strNum.substr(i,1)!=",")
   {
     newStrNum = newStrNum + strNum.substr(i,1);
   }
   
 }
 //alert(newStrNum);
 strNum = newStrNum;
 var tag = true;
 if(//D/.test(strNum)) //if iput is not a num then clear the input box and reinput again
 {  
   alert('Only integer is allowed');
   this.document.getElementById("money").value='';
   tag = false;
 }
 var length = strNum.length;
 var mod = length%3;
 var temp = "";
   
 if(length>=4 && tag) //only the length > 4 then run this process
 {
   if(mod==1)
   {
     temp = strNum.substr(0,1)+",";
     length = length -1;
     newStrNum = strNum.substr(1,length); // get the other numbers

   }
   if(mod==2)
   {
     temp = strNum.substr(0,2)+",";
     length = length -2;
     newStrNum = strNum.substr(2,length); // get the other numbers

   }
   if(mod==0)
   {
     newStrNum = strNum;
   }
   for(i=0;i<length;i=i+3)
   {
     temp += newStrNum.substr(i,3)+",";  
   }
   temp = temp.substr(0,temp.length-1);
   this.document.getElementById("money").value=temp;
   //alert(temp);
 }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值