input輸入框價格限定:只能輸入正數,小數點后兩位,不出現多個小數點,0開頭后面不接數字(vue做的)


1.給input綁定keyup函數:

<input
                type="text"
                class="form-control"
                id="inputEmail3"
                v-model="price"
                placeholder="請輸入價格"
               @keyup="priceFormat"
              />
 
2.編寫priceFormat函數:
priceFormat(){
         //非數字和小數點去掉     
        this.price=this.price.replace(/[^0123456789.]/,"") //之前沒注意寫錯了!!!!
        //防止無輸入無限個“.”
        this.price=this.price.replace(/\.+/ ,".")
        //在不是“0.”開頭的字符進行修改:“01”=>1
        if(this.price.charAt(0)=="0"&&this.price.charAt(1)!="."&&this.price.length>=2){
          this.price=this.price.replace(/0/ ,"")
        }
        //獲取第一個小數點的索引值
        var index=this.price.indexOf('.')
        //獲取最后一個小數點的索引值
        var lastIndex=this.price.lastIndexOf('.')
        //判斷小數點是不是開頭,如果是開頭,則去除
        if(index==0){
          this.price=this.price.replace(/\./ ,"")
        }
        //只允許小數點后面有2位字符
        if(index>=1){
          this.price=this.price.substring(0,index+3)          
        }
        //防止小數點后面又出現小數點
        if(index!=lastIndex){
          this.price=this.price.substring(0,index+2) 
        }
           
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM