html程式碼
<input type="text" onkeyup="clearNoNum(this)">
js程式碼
function clearNoNum(obj) {
var str,num,arr,len,bool;
obj.style.imeMode =`disabled` //禁止輸入法
obj.value = obj.value.replace("-", "$#$").replace(/-/g, "").replace("$#$","-");
obj.value = obj.value.replace(".", "$#$").replace(/./g, "").replace("$#$",".");
arr = obj.value.substring(0,1);
num = /^[0-9]*$/.test(arr);
len = obj.value.substring("0",1);
if( ((arr == "-") || (num == true && arr !== "0" )) || /^[0-9]*$/.test(obj.value) && len !== "0"){
bool = obj.value.slice(1).indexOf("-");
if(/^[0-9]*$/.test(bool)){
obj.value = null
}
obj.value = obj.value.replace(/^(-)*(d+).(dd).*$/, `$1$2.$3`);// 只能輸入兩個小數
obj.value = obj.value.replace(/[^-?d.]/g, ""); // 清除"數字"和"."和"-"以外的字元
if(obj.value !== "-" && obj.value !== "" & obj.value !== null){
var val = parseFloat(obj.value);
if (val >= 100000000000000000) {
obj.value = "99999999999999.99";
}
console.log(obj.value) //最終值
}
}else{
obj.value = null;
}
}
寫的不好!
希望大神們指點
錯誤或者可以簡寫的地方