//第一种方式
_(function(){
$('input[util="num"]').each(function(){
var self = $(this),
_self = this,
reg = /^[\-\+]?((\d+)([\.,](\d{3}))*([\.](\d+))?|([\.,](\d+))?)$/;
$(this).bind({
focus : function(){
self.val(self.val().split(',').join(''));
},
blur : function(){
if(!reg.test( self.val() )){
alert("您输入的值有误,只能输入整数!");
_self.select();
} else {
var arr = self.val().split('.'),
num = arr[0],
num2 = null;
if(arr.length > 1){
num2 = arr[1];
}
if(num.length > 3){
var _arr = num.split('').reverse(),
len = _arr.length,
page = Math.ceil(len / 3),
str = '';
for(var i=0; i<page; i++){
if(i*3 < len) str += _arr[i*3];
if(i*3+1 < len) str += _arr[i*3+1];
if(i*3+2 < len) str += _arr[i*3+2];
str += ',';
}
str = str.substring(0, str.length-1)
.split('').reverse().join('');
if(num2 !== null){
str += '.' + num2;
}
self.val(str);
}
}
}
});
});
});
?
在表单里加入 util=“num”?
<input type="text" util="num" />
<input type="text" util="num" />
<input type="text" util="num" />
<input type="text" util="num" />
?
//第二种方式
_(function(){
reg = /^[\-\+]?((\d+)([\.,](\d{3}))*([\.](\d+))?|([\.,](\d+))?)$/;
var s;
$('input[util="num"]').each(function(){
$(this).bind("blur",function(){
s = $(this).val();
dh = /,/;
while (dh.test(s)) {
s = s.replace(dh, "");
}
if (!reg.test(s)) {
alert("您输入的可能不是数字");
return false;
}
s = s.replace(/^(\d*)$/, "$1.");
s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
s = s.replace(".", ",");
var re = /(\d)(\d{3},)/;
while (re.test(s)) {
s = s.replace(re, "$1,$2");
}
s = s.replace(/,(\d\d)$/, ".$1");
$(this).val(s.replace(/^\./, "0."));
});
});
});
?