3
I’m developing a web application on the platform. NET and I thought of making the user type the zip code of his address and automatically he would fill the text boxes with data of street, neighborhood, city and state. But in my code it doesn’t work, I don’t know why.
Here is my code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Novo Registro</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
<script src="https://fiddle.jshell.net/js/lib/dummy.js"></script>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
$("#txtCPF").keydown(function(){
try {
$("#txtCPF").unmask();
} catch (e) {}
var tamanho = $("#txtCPF").val().length;
if(tamanho < 11){
$("#txtCPF").mask("999.999.999-99");
} else if(tamanho >= 11){
$("#txtCPF").mask("99.999.999/9999-99");
}
});
}//]]>
</script>
<!-- Adicionando Javascript -->
<script type="text/javascript">
function limpa_formulario_cep() {
//Limpa valores do formulário de cep.
document.getElementById("#txtRua").value=("");
document.getElementById('#txtBairro').value=("");
document.getElementById('#txtCidade').value=("");
document.getElementById('#txtEstado').value=("");
}
function meu_callback(conteudo) {
if (!("erro" in conteudo)) {
//Atualiza os campos com os valores.
document.getElementById('#txtRua').value=(conteudo.logradouro);
document.getElementById('#txtBairro').value = (conteudo.bairro);
document.getElementById('#txtCidade').value = (conteudo.localidade);
document.getElementById('#txtEstado').value = (conteudo.uf);
} //end if.
else {
//CEP não Encontrado.
limpa_formulario_cep();
alert("CEP não encontrado.");
}
}
function pesquisacep(valor) {
//Nova variável "cep" somente com dígitos.
var cep = valor.replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep != "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
document.getElementById('#txtRua').value = "...";
document.getElementById('#txtBairro').value = "...";
document.getElementById('#txtCidade').value = "...";
document.getElementById('#txtEstado').value = "...";
//Cria um elemento javascript.
var script = document.createElement('script');
//Sincroniza com o callback.
script.src = '//viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';
//Insere script no documento e carrega o conteúdo.
document.body.appendChild(script);
} //end if.
else {
//cep é inválido.
limpa_formulario_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulario_cep();
}
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Cadastro de Clientes - Novo Registro</h3>
<h5>Obs.: Campos sinalizados com *(asterisco) são de preenchimento obrigatório!</h5>
<asp:TextBox ID="txtNome" runat="server" Width="384px" placeholder="Nome*"></asp:TextBox>
<asp:RequiredFieldValidator ID="txtNomeValidator" runat="server" ControlToValidate="txtNome" Display="Dynamic" ForeColor="Red" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:TextBox ID="txtFantasia" runat="server" Width="384px" placeholder="Fantasia"></asp:TextBox><br />
<asp:TextBox ID="txtCPF" runat="server" Width="384px" placeholder="CPF ou CNPJ"></asp:TextBox><br />
<asp:TextBox ID="txtCEP" runat="server" Width="70px" placeholder="CEP*" AutopostBack="true"></asp:TextBox><br />
<asp:TextBox ID="txtLogradouro" runat="server" Width="305px" placeholder="Logradouro"></asp:TextBox><br />
<asp:TextBox ID="txtNumero" runat="server" Width="80px" placeholder="Número"></asp:TextBox><br />
<asp:TextBox ID="txtComplemento" runat="server" Width="100px" placeholder="Complemento"></asp:TextBox><br />
<asp:TextBox ID="txtBairro" runat="server" Width="200px" placeholder="Bairro"></asp:TextBox><br />
<asp:TextBox ID="txtCidade" runat="server" Width="200px" placeholder="Cidade"></asp:TextBox><br />
<asp:TextBox ID="txtEstado" runat="server" Width="50px" placeholder="Estado"></asp:TextBox><br />
<asp:Button ID="btnSalvar" runat="server" Text="Salvar"/>
</div>
</form>
</body>
</html>
my code-Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class insert : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtCEP.Attributes.Add("onblur", "pesquisacep(this.value);");
}
}
It works on JSBIN: http://output.jsbin.com/baxuyumace
Could someone help me with this, please?
Hello Cassia, welcome to Stackoverflow in English. Could you be more specific, because it doesn’t work? Is there an error message? Try to isolate the problem further.
– gato
Thank you, drmcarvalho :). So, I go to type the zip code and the screen updates, but the fields are not filled :(
– Cássia