1. 程式人生 > 其它 >input框限制輸入金額

input框限制輸入金額

HTML:

<input type="tel" class="capital mui-input-clear" value="0.00"> <div class="redbag_box4_son">¥0.00</div>

JS:

$(document).ready(function(){ // 限制文字框只能輸入數字和小數點 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(".redbag_box4_son").innerHTML = '¥'+integerNum+decimalNum; }else{ document.querySelector(".redbag_box4_son").innerHTML = logNum.replace(/\d(?=(\d{3})+$)/g,'$&,'); } }); })

參考連結:https://www.cnblogs.com/kousuke/p/perfect-input-for-money.html