jquery控制input只能輸入數字和兩位小數(轉)
阿新 • • 發佈:2019-02-02
知識點一
直接上程式碼:
function num(obj){
obj.value = obj.value.replace(/[^\d.]/g,""); //清除"數字"和"."以外的字元
obj.value = obj.value.replace(/^\./g,""); //驗證第一個字元是數字
obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一個, 清除多餘的
obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
obj.value = obj.value .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能輸入兩個小數
}
限制只能保留兩位小數點
<input type="text" onkeyup="num(this)" size="10"/>元
限制只能輸入數字
<input type="text" onkeyup='this.value=this.value.replace(/\D/gi,"")'/>
限制只能輸入數字、字母和”-“
<input type="text" onkeyup='value=value.replace(/[^A-Za-z0-9\-]+/g,"")' />