获得焦点并输入效果,失去焦点效果
js代码:
<script>
// 格式化数字成0,000.00
function formatNumber(value) {
var result = "";
var valueParts = value.split(".");
var mostSignificationDigit = valueParts[0].length -1; // 最高有效数字位,默认为个位
var intervalOfDigit = 0; // 逗号之间的位数
var digit, countOfSignificationDigit;
for (var i = valueParts[0].length -1; i >= 0; i--) {
digit = valueParts[0][i];
result = digit + result;
if (digit != "0") {
mostSignificationDigit = i;
}
if (3 == ++intervalOfDigit) {
result = "," + result;
intervalOfDigit = 0;
}
}
if (mostSignificationDigit == -1) {
result = "0";
}
else {
countOfSignificationDigit = valueParts[0].length - mostSignificationDigit;
if (countOfSignificationDigit > 3) {
result = result.substring(result.length - (countOfSignificationDigit%3 == 0 ? countOfSignificationDigit/3 - 1 : countOfSignificationDigit/3) - countOfSignificationDigit);
}
else {
result = result.substring(result.length - countOfSignificationDigit);
}
}
if (valueParts.length == 2) {
result += ".";
var temp = 2 - valueParts[1].length; // 是否需要补0
for (var i = 0; i < temp; i++) {
valueParts[1] += "0"
}
result += valueParts[1].substring(0, 2);
}
else {
result += ".00";
}
return result;
}
// 鼠标再次聚焦文本域,就清除货币格式,显示无格式的数字
function clearAllFormat(obj){
if(obj!=null&&$(obj).val()!=null&&$(obj).val().trim().length>0){
var waitToDeleteCommaNumber = $(obj).val();
var newInputValue = waitToDeleteCommaNumber.replace(/,/g,"");
$(obj).val(newInputValue.toString());
return newInputValue.toString();
}
}
// 验证是否为浮点数
function checkNumberIsLegal22(obj){
if(!/^[0-9]+(\.[0-9]+){0,1}$/.test(obj)){
return false;
}
return true;
}
// 格式化金额类数字,每三位用逗号分隔,显示的是用逗号分隔的格式化形式
function formatMoneyByComma(obj){
if(obj!=null&&$(obj).val().trim().length>0&&checkNumberIsLegal22($(obj).val())){
// 格式化之前,先清除格式
clearAllFormat(obj);
if($(obj).val()){
var currentNumber = $(obj).val();
$(obj).val(formatNumber(currentNumber));
}
}
}
</script>
jsp:
<input id="partoutAmount" name="partoutAmount" class="c2" οnfοcus="clearAllFormat(this)" οnblur="formatMoneyByComma(this)" maxlength="20" style="text-align:right;height:28px">