js控制input框只能输入数字和一位小数点和小数点后面两位小数
html代码
<input id="money" type="number" step="1"
pattern="number" class="form-control" placeholder="¥ 输入付款金额"
aria-label="Example text with button addon">
js代码
// 金额计算
$("#money").on('input propertychange',function(){
//如果输入非数字,则替换为''
this.value = this.value.replace(/[^\d\.]/g, '');
//必须保证第一个为数字而不是.
this.value = this.value.replace(/^\./g,'');
//保证只有出现一个.而没有多个.
this.value = this.value.replace(/\.{2,}/g,'.');
//保证.只出现一次,而不能出现两次以上
this.value = this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
//只能输入两位小数
this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
if (this.value.indexOf(".") < 0 && this.value != "") { //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
this.value = parseFloat(this.value);
}
})
$("#money").blur(function(){
//如果输入框为空,则替换为0.00
if(this.value == ""){
this.value = "0.00";
}
})
vue限制
<input ref="price" type="text" @input="handleAmountChange" v-model.number.trim="totalval" />
js 代码
handleAmountChange(e) {
//过滤e字符
e.target.value = e.target.value.replace("e", "");
//判断输入是数字和.
e.target.value = e.target.value.replace(/[^\d.]/g, "");
this.totalval = e.target.value;
// 必须保证第一个为数字而不是.
this.totalval = this.totalval.replace(/^\./g, "0.");
// 保证只有出现一个.而没有多个.
this.totalval = this.totalval.replace(/\.{2,}/g, ".");
// 保证.只出现一次,而不能出现两次以上
e.target.value = e.target.value
.replace(".", "$#$")
.replace(/\./g, "")
.replace("$#$", ".");
//只能输入两个小数
this.totalval = this.totalval.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3");
},