輸入框只能輸入負數,整數,2位小數(鍵盤彈起事件)

html代碼html

<input type="text" onkeyup="clearNoNum(this)">

js代碼this

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+)\.(\d\d).*$/, '$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; 
   }
}

寫的很差!
但願大神們指點
錯誤或者能夠簡寫的地方code

相關文章
相關標籤/搜索