Skip to content

Instantly share code, notes, and snippets.

@temberature
Last active May 28, 2018 03:35
Show Gist options
  • Save temberature/7aa605a3e754d743ec3eed856a4f05ac to your computer and use it in GitHub Desktop.
Save temberature/7aa605a3e754d743ec3eed856a4f05ac to your computer and use it in GitHub Desktop.
var numberInput = {
options: {
$wrap: $('.numberCheckInput'),
headZero: false,
decimalPlace: 2,
min: 0,
max: 0,
required: true,
tips: {
max: "金额不能高于",
required: '金额不能为空'
},
afterDelete: $.noop,
afterCheck: $.noop
},
cache: {},
init: function (options) {
var me = this,
ca = me.cache;
$.extend(me.options, options);
ca.$quickWrap = me.options.$wrap.find('.quick-wrap');
ca.$input = ca.$quickWrap.find('input');
ca.$tip = me.options.$wrap.find('.tip');
me.initCheck();
me.initQuickDelete();
},
initCheck: function () {
var me = this,
ca = me.cache;
ca.$input
.bindLiveCheck(/[^\d\.]/g, function(e) {
var v = this.value,
w = $.trim(v)
.replace(/\.+/g, "\.")
.replace(new RegExp('\\.(\\d{0,' + me.options.decimalPlace + '}).*$'), ".$1")
.substr(0, 12);
if (v != w) {
this.value = w;
}
me.checkBoundary();
})
.on('blur', function () {
var v = this.value,
w = $.trim(v)
.replace(/^\./, "0.");
if (!me.options.headZero) {
w = w.replace(/^0+(\d)/, "$1");
}
if (v != w) {
this.value = w;
}
me.checkBoundary();
})
.on('keypress keydown', function (e) {
var code = e.charCode || e.keyCode;
if (+this.value === 0&&String.fromCharCode(code) === '0') {
return false;
}
});
},
initQuickDelete: function () {
var me = this,
ca = me.cache;
style.use();
ca.$quickWrap
.quickDelete({
sameWidth: false
})
.find('input')
.bind({
afterDelete: function() {
ca.$tip.text("");
me.options.afterDelete();
}
});
},
checkBoundary: function () {
var me = this,
ca = me.cache;
var tip,
value = +ca.$input.val();
ca.$tip.text('');
ca.value = value;
if (ca.$input.val() === '') {
ca.value = false;
} else {
if (value === 0) {
if (me.options.required) {
tip = me.options.tips.required;
ca.value = false;
}
}
if (value < me.options.min) {
tip = '金额不能低于' + me.options.min + '元';
ca.value = false;
}
if (value > me.options.max) {
tip = me.options.tips.max + me.options.max + '元';
ca.value = false;
}
if (String(value).length > 12) {
tip = "已经输入12位了,不能输入更多";
ca.value = false;
}
if (tip) {
ca.$tip.text(tip);
}
}
me.options.afterCheck();
return ca.value;
},
val: function (value) {
var me = this,
ca = me.cache;
ca.$input.val(value);
ca.$tip.text("");
ca.value = value;
return ca.value;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment