The js code is not well written! I hope the experts can point out the errors or places that can be abbreviated."/> The js code is not well written! I hope the experts can point out the errors or places that can be abbreviated.">

Home  >  Article  >  Web Front-end  >  The input box can only enter negative numbers, integers, and 2 decimal places (keyboard pop-up event)

The input box can only enter negative numbers, integers, and 2 decimal places (keyboard pop-up event)

php是最好的语言
php是最好的语言Original
2018-08-06 15:35:132247browse

html代码

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

js代码

   function clearNoNum(obj) {
       var str,num,arr,len,bool; 
       obj.style.imeMode =&#39;disabled&#39;   //禁止输入法
    
       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).*$/, &#39;$1$2.$3&#39;);// 只能输入两个小数     
       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; 
   }
}

写的不好!
希望大神们指点    
错误或者可以简写的地方

相关文章:

解析html输入框只能输入数字和只能输入字母数字

限制文本框只能输入数字,小数点,英文字母,汉字

The above is the detailed content of The input box can only enter negative numbers, integers, and 2 decimal places (keyboard pop-up event). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn