扩充 extjs 4.2 的 NumberField 使其支持千位分隔符显示
扩展 extjs 4.2 的 NumberField 使其支持千位分隔符显示
Ext.define('BM.ux.MoneyFiled', { extend:'Ext.form.NumberField', alias: 'widget.moneyfield', trulyValue:null, setValue: function(v){ if(isNaN(v)){ this.setRawValue(''); this.trulyValue = null; }else{ this.setRawValue(this.getFormatValue(v)); this.trulyValue = v; } }, getFormatValue:function(v){ v = typeof v == 'number' ? v : Number(v); v = isNaN(v) ? '' : formatMoney(v); return v; }, getSubmitValue: function() { return this.trulyValue; }, onChange: function(v) { this.toggleSpinners(); this.callParent(arguments); this.trulyValue = this.parseValue(v); }, validateValue: function(value){ var num = this.parseValue(value); if (isNaN(num) && num.length > 0) { this.markInvalid(String.format(this.nanText, value)); return false; } return Ext.form.NumberField.superclass.validateValue.call(this, num); }, onBlur : function() { this.setValue(this.trulyValue); }, onFocus:function(){ this.setRawValue(this.trulyValue); }, parseValue: function(value){ value = parseFloat(String(value).replace(this.decimalSeparator, ".").replace(/,/g, "")); return isNaN(value) ? '' : value; }, getErrors: function(value) { return Ext.form.NumberField.superclass.getErrors.call(this,this.trulyValue); } });
/*将数字转换为千位符*/ function formatMoney(v) { if(isNaN(v)){ return v; } v = (Math.round((v - 0) * 100)) / 100; v = (v == Math.floor(v)) ? v + "" : ((v * 10 == Math.floor(v * 10)) ? v + "0" : v); v = String(v); var ps = v.split('.'); var whole = ps[0]; var sub = ps[1] ? '.' + ps[1] : ''; var r = /(\d+)(\d{3})/; while (r.test(whole)) { whole = whole.replace(r, '$1' + ',' + '$2'); } v = whole + sub; return v; }
交互过程:在控件失去焦点的时候显示为千位符显示,鼠标移入变为正常数值显示。
开发过程记录:
1.重写getSubmitValue 让表单提交的时候获取的是真实的值
2.在onChange事件中动态更新 trulyValue
3.重写getErrors方法使得表单验证的时候获取的是真实的值