代码:
/**
* 输入内容只能是数值,包括正负数,整数,小数,分数和零
*/
$.fn.validateNumber = function (defaultValue) {
$(this).keypress(function (e) {
var keyCode = e.which;
if (keyCode >= 45 && keyCode <= 57)
return true;
else{
return false;
}
}).change(function () {
var content = $(this).val().trim();
var length = content.length;
var tmp = '';
var pointPos = -1;//第一个'.'的位置code=46
var fenPos = -1;//第一个'/'的位置code=47
for(var i = 0; i < length; i++){
var code = content.charCodeAt(i);
if(code > 65295 && code < 65306){//全角
code = code - 65248;
}
if(code == 46 && pointPos == -1 && fenPos == -1 && i != length - 1){
pointPos = i;
if(pointPos == 0){
tmp = tmp + '0' + String.fromCharCode(code);
}else{
tmp += String.fromCharCode(code);
}
continue;
}
if(code == 47 && fenPos == -1 && pointPos == -1 && i != length - 1){
fenPos = i;
if(fenPos == 0){
tmp = tmp + '1' + String.fromCharCode(code);
}else{
tmp += String.fromCharCode(code);
}
continue;
}
if((code >= 48 && code <= 57) || (i == 0 && code == 45 && length != 1)){
tmp += String.fromCharCode(code);
continue;
}
}
if(defaultValue && (tmp == '' || tmp == '-')){
tmp = defaultValue;
}
$(this).val(tmp);
});
}
$(".validateNumber").validateNumber();