/*
jQuery 文本框數值輸入驗證
author: 陳日紅@杭州
date: 2013-11-15
version: v1.1
IE9,FF,CHROME 測試通過
使用說明:
1、文本框添加 max_vlaue 自定義屬性後,可以驗證輸入值必須小於等於 max_value
調用方法:
1、允許小數:$(":text").just_num({ decimal: true,digits:2,sum:true });
2、不允許小數:$(":text").just_num();
*/
; (function ($) {
//擴展
$.fn.extend({
//插件名稱
just_num: function (options) {
//默認參數
var defaults = {
decimal: false,
digits:2,
sum:false
};
//覆蓋默認參數
var opts = $.extend(defaults, options);
var $this = this;
function _fn(_this){
if(opts.decimal){
_this.value = _this.value.replace(/[^\d\.]/g, '').replace(/^\./g,'0.').replace(/\.{2,}/g,".").replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}else{
_this.value = _this.value.replace(/[^\d]/g, '');
}
if(_this.value != '0' && _this.value != ''){
//防止出現 00000=====
if( opts.decimal && _this.value.substr(_this.value.length - 1,1) == '.'){
_this.value = parseFloat(_this.value, 10) + '.';
}
else{
_this.value = parseFloat(_this.value, 10);
}
//==============
var max_value = parseFloat(_this.getAttribute('max_value'), 10);
if(!isNaN(max_value)){
if (_this.value > max_value) {
_this.value = max_value;
}
}
if(_this.value.indexOf('.') != -1 && (_this.value.length - _this.value.indexOf('.') - 1 ) > opts.digits ){
_this.value = _this.value.substr(0,_this.value.indexOf('.') + 1 + opts.digits);
}
}else{
_this.value = 0;
}
if(opts.sum)
{
get_sum(0);
}
}
function get_sum(sum_value){
$this.each(function(idx, obj){
var val = parseFloat(obj.value, 10);
if (!isNaN(val)) {
sum_value = sum_value * 1 + val * 1;
}
if(idx == $this.length - 1)
{
if(opts.decimal){
sum_value = parseFloat(sum_value, 10).toFixed(opts.digits);
}
var obj = document.getElementById("numberic_sum");
if(obj){
if(obj.getAttribute("type") == "text"){
obj.value = sum_value;
}else{
obj.innerHTML = sum_value;
}
}else{
alert('jQuery.numberic.js:\n\n 無法保存求和結果:找不到 id = numberic_sum 的 element ! ');
}
}
});
}
this.each(function () {
var t = this;
_fn(t);
$(t).bind('focus', function (evt) {
if (t.value == 0) {
t.value = '';
}
});
$(t).bind('paste',function(evt){
return false;
});
$(t).bind('blur', function (evt) {
if (t.value == '')
{
t.value = 0;
}
else{
if(opts.decimal){
t.value = parseFloat(t.value, 10).toFixed(opts.digits);
}
}
});
$(t).bind('keyup', function () {
_fn(t);
});
});
}
});
})(jQuery);
下載地址:下載