价格输入框:
<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";
}
})