var Postcode = function(url, address, postcode, onSetted) { this.url = url; this.address = address; this.postcode = postcode; this.onSetted = function(self, value){}; if (typeof onSetted == 'function') { this.onSetted = onSetted; } }; Postcode.prototype.init = function() { var _self = this; this.address.live('keyup', function() { if (this.value.length <= 3) return; var _trimPostcode = function(postcode) { if (typeof postcode == 'undefined') return ''; return postcode.trim().split('-').join(''); }; var _isSetPostcode = function(postcode) { return (_trimPostcode(postcode).length == 7); }; if (_isSetPostcode(_self.postcode.val())) return; $.ajax(_self.url, { type: 'post', data: { address : this.value }, cache: false, success: function(data) { if (data.length != 7) return; data_trimmed = _trimPostcode(_self.postcode.val()); if (data_trimmed == data) return; if (_isSetPostcode(data_trimmed)) return; postcode = data.substr(0, 3) + '-' + data.substr(3, 4); _self.postcode.val(postcode); if (typeof _self.onSetted == 'function') { _self.onSetted(_self, postcode); } } }) }); };