本文主要是介绍JS限制文本框输入金额并保留两位小数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS限制文本框输入金额并保留两位小数</title>
<script type="text/javascript">/**
* 实时动态强制更改用户录入
* arg1 inputObject
**/
function amount(th){var regStrs = [['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上,但首位为0['[^\\d\\.]+$', ''], //禁止录入任何非数字和点['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上];for(var i=0; i<regStrs.length; i++){var reg = new RegExp(regStrs[i][0]);th.value = th.value.replace(reg, regStrs[i][1]);}
}/**
* 录入完成后,输入模式失去焦点后对录入进行判断并强制更改,并对小数点进行0补全
* arg1 inputObject
**/
function overFormat(th){var v = th.value;if(v === ''){v = '0.00';}else if(v === '0'){v = '0.00';}else if(v === '0.'){v = '0.00';}else if(/^0+\d+\.?\d*.*$/.test(v)){v = v.replace(/^0+(\d+\.?\d*).*$/, '$1');v = inp.getRightPriceFormat(v).val;}else if(/^0\.\d$/.test(v)){v = v + '0';}else if(!/^\d+\.\d{2}$/.test(v)){if(/^\d+\.\d{2}.+/.test(v)){v = v.replace(/^(\d+\.\d{2}).*$/, '$1');}else if(/^\d+$/.test(v)){v = v + '.00';}else if(/^\d+\.$/.test(v)){v = v + '00';}else if(/^\d+\.\d$/.test(v)){v = v + '0';}else if(/^[^\d]+\d+\.?\d*$/.test(v)){v = v.replace(/^[^\d]+(\d+\.?\d*)$/, '$1');}else if(/\d+/.test(v)){v = v.replace(/^[^\d]*(\d+\.?\d*).*$/, '$1');ty = false;}else if(/^0+\d+\.?\d*$/.test(v)){v = v.replace(/^0+(\d+\.?\d*)$/, '$1');ty = false;}else{v = '0.00';}}th.value = v;
}
</script>
</head>
<body>
<input type="text" name="city" value="" onKeyUp="amount(this)" onBlur="overFormat(this)" />
</body>
</html>
转载:http://blog.csdn.net/u014676619/article/details/53636819?utm_source=itdadao&utm_medium=referral
这篇关于JS限制文本框输入金额并保留两位小数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!