我使用keydown和keypress,此代码仅适用于chrome但不适用于firefox。
第一个功能是用户只能使用数字,小键盘,退格键和制表符。另一个功能是,当用户键入数字时,它将自动更改为十进制
默认 - > 0.00
输入1 - > 0.01
输入0 - > 0.10
输入0 - > 1.00
你可以找到我的演示 here
$('#txtInput').keydown(function(event) {
var Key = event.which;
//number
if (Key >= 48 && Key <= 57) {
return true;
}
//numpad
else if (Key >= 96 && Key <= 105) {
return true;
}
//backspace,tab
else if (Key >= 8 && Key <= 9) {
return true;
}
else return false;
});
$(document).ready(function(){
$('#txtInput').keypress(function(e){
var value = $('#txtInput').val().toString();
var number = null;
if(value == '')
value = '0.00';
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
number = e.which - 48;
break;
default:
e.preventDefault();
break;
}
var dotIndex = value.indexOf('.');
if(number === null)
{
value = value.substr(0,dotIndex-1) + '.' + value.substr(dotIndex -1,1) + value.substr(dotIndex+1,1);
if(value.indexOf('.') ==0)
{
value = '0' + value;
}
}
else
{
value = value.substr(0,dotIndex) + value.substr(dotIndex+1,1) + '.' + value.substr(dotIndex+2);
value += number.toString();
value = value.replace(/^0+/,'');
if(value.indexOf('.') == 0)
{
value = '0' + value;
}
}
$('#txtInput').val(value);
e.preventDefault();
}).keypress(function(e){
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
e.preventDefault();
break;
}
});
});