原生js限制input輸入金額
阿新 • • 發佈:2018-11-15
- <!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
- 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>