input輸入框輸入金額校驗
阿新 • • 發佈:2018-11-10
價格輸入框:
<input type="text" id="price" name="price" class="form-control"/>
js校驗只能輸入帶兩位小數的金額:
$("#price").on('input propertychange',function(){ //如果輸入非數字,則替換為'' this.value = this.value.replace(/[^\d\.]/g, ''); //必須保證第一個為數字而不是. this.value = this.value.replace(/^\./g,''); //保證只有出現一個.而沒有多個. this.value = this.value.replace(/\.{2,}/g,'.'); //保證.只出現一次,而不能出現兩次以上 this.value = this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.'); //只能輸入兩位小數 this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); })
propertychange和input事件,這兩個事件其實是一回事,只是不同的標準罷了,可以同時繫結,input是標準的瀏覽器(W3C)事件,一般應用於input元素,當input的value發生變化就會發生,無論是鍵盤輸入還是滑鼠,重點是黏貼的改變都能及時監聽到變化;propertychange是IE專屬的事件,只要當前物件屬性值發生改變就能觸發。
再加一個blur事件會更好:
$("#price").blur(function(){
//如果輸入框為空,則替換為0.00
if(this.value == ""){
this.value = "0.00";
}
})