Problem with script

Hi!!

I’m trying to use a script to get information from an API. This script is the same I’m already using in Webflow, but it’s not working here.

Does anyone know how to solve it ?

$(document).ready(function() {
    // Máscara para CNPJ
    $('#inputCNPJ').inputmask('99.999.999/9999-99');
    // Máscara para CEP
    $('#inputCEP').inputmask('99999-999');
    // Máscara para Celular
    $('#CelularR, #CelularF').inputmask('(99) 99999-9999');
});

            // Consultar CNPJ com proxy CORS
            $('#inputCNPJ').on('blur', function() {
                const cnpj = $(this).val().replace(/\D/g, '');
                if (cnpj.length === 14) {
                    const proxyUrl = 'https://cors-anywhere.herokuapp.com/'; // Proxy CORS
                    const apiUrl = `https://receitaws.com.br/v1/cnpj/${cnpj}`;

                    $.getJSON(proxyUrl + apiUrl, function(data) {
                        if (data.nome) {
                            $('#inputRS').val(data.nome);
                            $('#inputRUA').val(data.logradouro);
                            $('#inputNumero').val(data.numero);
                            $('#inputComp').val(data.complemento);
                            $('#inputBairro').val(data.bairro);
                            $('#inputCidade').val(data.municipio);
                            $('#inputUF').val(data.uf);
                            $('#inputCEP').val(data.cep.replace(/(\d{5})(\d{3})/, '$1-$2'));
                        } else {
                            alert('CNPJ não encontrado ou inválido.');
                        }
                    }).fail(function() {
                        alert('Erro ao consultar CNPJ. Tente novamente.');
                    });
                }
            });

            // Consultar CEP
            $('#inputCEP').on('blur', function() {
                const cep = $(this).val().replace(/\D/g, '');
                if (cep.length === 8) {
                    $.getJSON(`https://viacep.com.br/ws/${cep}/json/`, function(data) {
                        if (!data.erro) {
                            $('#inputRUA').val(data.logradouro);
                            $('#inputBairro').val(data.bairro);
                            $('#inputCidade').val(data.localidade);
                            $('#inputUF').val(data.uf);
                        } else {
                            alert('CEP não encontrado.');
                        }
                    }).fail(function() {
                        alert('Erro ao consultar CEP. Tente novamente.');
                    });
                }
            });

Thank you.

Hey, I fixed a script on your website. Writing JS on divhunt is a bit different, in a way, you need to think that this is SPA, and pages are not being refreshed when you are browsing through website.

We will create a detailed explanation (video tutorial) on this topic soon.

But in your case, problem was that in time of loading your JS blur events, these elements don’t exist on a page, they are loaded after your JS.

So in jquery theres one good solution when working with dynamicly loaded elements:

Instead of writing:

$('#inputCNPJ').on('blur', function() {

Write it like this, and in our JS files, use event “website on load”.

$(document).on('blur','#inputCEP',function(){

This ensures the event works even if the element is loaded dynamically, which is important for SPAs or dynamically updated content.

Hey Pakic,

I’ve updated the code, but it’s still not working :confused:
Maybe I’m doing something wrong.

Follow:

// Consultar CNPJ com proxy CORS
$(document).on('blur', '#inputCNPJ', function() {
    console.log("inputCNPJ", $(this).val());
    const cnpj = $(this).val().replace(/\D/g, ''); // Remove caracteres não numéricos
    if (cnpj.length === 14) {
        const proxyUrl = 'https://corsproxy.io/?'; // Proxy CORS alternativo
        const apiUrl = `https://receitaws.com.br/v1/cnpj/${cnpj}`;

        $.getJSON(proxyUrl + encodeURIComponent(apiUrl), function(data) {
            if (data.nome) {
                $('#inputRS').val(data.nome);
                $('#inputRUA').val(data.logradouro);
                $('#inputNumero').val(data.numero);
                $('#inputComp').val(data.complemento);
                $('#inputBairro').val(data.bairro);
                $('#inputCidade').val(data.municipio);
                $('#inputUF').val(data.uf);
                $('#inputCEP').val(data.cep.replace(/(\d{5})(\d{3})/, '$1-$2')); // Aplica máscara no CEP
            } else {
                alert('CNPJ não encontrado ou inválido.');
            }
        }).fail(function() {
            alert('Erro ao consultar CNPJ. Tente novamente.');
        });
    } else {
        alert('CNPJ inválido. O CNPJ deve ter 14 dígitos.');
    }
});

// Consultar CEP
$(document).on('blur', '#inputCEP', function() {
    console.log("inputCEP", $(this).val());
    const cep = $(this).val().replace(/\D/g, ''); // Remove caracteres não numéricos
    if (cep.length === 8) {
        $.getJSON(`https://viacep.com.br/ws/${cep}/json/`, function(data) {
            if (!data.erro) {
                $('#inputRUA').val(data.logradouro);
                $('#inputBairro').val(data.bairro);
                $('#inputCidade').val(data.localidade);
                $('#inputUF').val(data.uf);
                $('#inputCEP').val(cep.replace(/(\d{5})(\d{3})/, '$1-$2')); // Aplica máscara no CEP
            } else {
                alert('CEP não encontrado.');
            }
        }).fail(function() {
            alert('Erro ao consultar CEP. Tente novamente.');
        });
    } else {
        alert('CEP inválido. O CEP deve ter 8 dígitos.');
    }
});

If I am watching correct website, code is being triggered on blur.
I put a console.log when this event happens and it is being triggered, you can see both in console and as an alert.

If something is not working, it is inside of that code, that API or something

Thank you @Pakic
It’s working :slight_smile:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.