公司某位领导的意见,用户输入数字的时候要将数据字换成美元的显示方法.
有两种思路,一种就是用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);
}
}