js 如何限制input只能输入数字小数点且只能输4位小数

如题,我现在有4个input,4个input从输入开始都有只能输入数字和小数点且小数点后只能输入4位小数的限制,如果输入的格式不对,比如我写了一个s进去,这个s就写不进去了,要用到key事件,应该如何解决,求解答

跃然一笑
浏览 2873回答 4
4回答

米脂

<input&nbsp; type="text" onkeyup="clearNoNum(this)">function clearNoNum(obj){&nbsp; &nbsp; &nbsp; &nbsp; obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符&nbsp; &nbsp; &nbsp; &nbsp; obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字而不是&nbsp; &nbsp; &nbsp; &nbsp; obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的&nbsp; &nbsp; &nbsp; &nbsp; obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");&nbsp; &nbsp; &nbsp; &nbsp; obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d\d).*$/,'$1$2.$3'); //只能输入两个小数&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $('input[name="buyMoney"]').val(accMul($('input[name="buyPrice"]').val(),$('input[name="buyVal"]').val()));&nbsp; &nbsp; &nbsp; &nbsp; $('input[name="saleMoney"]').val(accMul($('input[name="salePrice"]').val(),$('input[name="saleVal"]').val()));&nbsp; &nbsp; }&nbsp; &nbsp; // 解决浮点数&nbsp; &nbsp; function accMul(arg1,arg2){&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arg1 == undefined || arg2 == undefined){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var m=0,s1=arg1.toString(),s2=arg2.toString();&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{m+=s1.split(".")[1].length}catch(e){}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{m+=s2.split(".")[1].length}catch(e){}&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

不负相思意

正则验证一下就可以了/^(-?\d+)(\.\d{4})?$/

暮色呼如

<input id="input">var input = document.getElementById('input');var reg = /^\d+(\.)?\d{0,4}?$/;var oldValue = ''input.addEventListener('input',function(e){&nbsp; if(reg.test(e.target.value)){&nbsp;&nbsp; &nbsp; oldValue = e.target.value&nbsp; }else if(e.target.value){&nbsp; &nbsp; e.target.value = oldValue;&nbsp; } else{&nbsp; &nbsp; e.target.value = '';&nbsp; &nbsp; oldValue = '';&nbsp; }});input.addEventListener('change',function(e){&nbsp; if(e.target.value.endsWith('.')){&nbsp; &nbsp; e.target.value = e.target.value.slice(0,-1);&nbsp; &nbsp;}&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript