javascript 输入金额 检验

2018-08-15  本文已影响0人  ZhiPengTu
image.png

html

<div class="mui-input-row">
    <label>金额<span>(元)</span></label>
    <input type="tel" class="capital mui-input-clear" value="0.00">
</div>
<p class="logbox"></p>

javascript

/*投资本金仅能输入数字和小数点*/
var precapital;//存取到的值
document.querySelector('.capital').addEventListener('focus', function() {
    if (this.value == '0.00') {
        this.value = '';
    } else {
        this.value = this.value.replace(/\.00/, '').replace(/(\.\d)0/,'$1');
    }
    precapital = this.value;
});
document.querySelector('.capital').addEventListener('keyup', function() {

    this.value = this.value.replace(/^[\.]/, '').replace(/[^\d.]/g, '');
    if (this.value.split(".").length - 1 > 1) {
        this.value = precapital;
    }
    precapital = this.value;
});
document.querySelector('.capital').addEventListener('blur', function() {
    this.value = this.value.replace(/[\.]$/, '');
    this.value = this.value.replace(/(.*)\.([\d]{2})(\d*)/g,'$1.$2');
    this.value = Number(this.value).toFixed(2);
    var logNum = this.value.toString();
    if(logNum.match(/\./g) != null){
        integerNum = parseInt(logNum).toString().replace(/\d(?=(\d{3})+$)/g,'$&,');
        decimalNum = '.' + logNum.replace(/(.*)\.(.*)/g,'$2');
        document.querySelector(".logbox").innerHTML = integerNum+decimalNum;
    }else{
        document.querySelector(".logbox").innerHTML = logNum.replace(/\d(?=(\d{3})+$)/g,'$&,');
    }
});

var val=Number(precapital).toFixed(2);//处理取到的值
上一篇 下一篇

猜你喜欢

热点阅读