/* * jQuery autocomplete address - v1.0.0 * A jQuery plugin to autocomplete address using the correio's CEP * https://github.com/arthurfigueiredo/autocomplete-address * * Made by Arthur Figueiredo */ !function(a,b,c,d){function e(b,c){this.element=b,this.settings=a.extend({},g,c),this._defaults=g,this._name=f,this.init()}var f="autocompleteAddress",g={publicAPI:"https://viacep.com.br/ws/{{cep}}/json/",address:"",neighborhood:"",city:"",state:"",setReadonly:!0};a.extend(e.prototype,{init:function(){var b=this;this.$cep=a(this.element),this.$address=this.getData("autocomplete-address"),this.$neighborhood=this.getData("autocomplete-neighborhood"),this.$city=this.getData("autocomplete-city"),this.$state=this.getData("autocomplete-state"),this.currentCep=this.$cep.val(),this.$cep.mask&&this.$cep.mask("99999-999"),this.$cep.on("blur change keyup",function(){var c=a(this).val();c=c.replace(/\-|\./g,""),c&&b.currentCep!==c&&8===c.length&&(b.currentCep=c,b.sendRequest())})},getData:function(b){var c=a(this.settings[b.replace("autocomplete-","")]);return 0===c.length&&(c=a("."+b),0===c.length&&(c=a("[data-"+b+"]"))),c},sendRequest:function(){var b=this,c=this.currentCep.replace("-","");a.ajax({url:b.settings.publicAPI.replace("{{cep}}",c),type:"GET",dataType:"json",success:function(a){b.bindValues(a)}})},bindValues:function(a){this.$address.val(a.logradouro),this.$neighborhood.val(a.bairro),this.$state.is("select")?(this.$state.children('option:contains("'+a.uf+'")').prop("selected",!0),this.$state.next().hasClass("nice-select")&&this.$state.niceSelect("update")):this.$state.val(a.uf),this.$state.change(),this.$city.is("select")?(this.$city.children('option:contains("'+a.localidade+'")').prop("selected",!0),this.$city.data("select",a.localidade)):this.$city.val(a.localidade),this.$city.change(),this.settings.setReadonly&&this.checkStatusField([this.$address,this.$neighborhood,this.$city,this.$state])},checkStatusField:function(b){for(var c,d,e=b.length;e--;)c=a(b[e]),d=c.val(),b[e].length>0&&d&&d.match(/[a-z]/i)?c.addClass("disabled").prop("readonly",!0):c.removeClass("disabled").prop("readonly",!1)}}),a.fn[f]=function(b){return this.each(function(){a.data(this,"plugin_"+f)||a.data(this,"plugin_"+f,new e(this,b))}),this}}(jQuery,window,document);