Function . Blur() does not run with dynamically added element

Asked

Viewed 18 times

0

I have a select that when selecting the option Brazil he adds a input for ZIP CODE and when selecting France he adds a input for ZIP. With the value of these inputs I will query the API as an example I will use the viacep. However Blur does not work, I type the zip code in and nothing happens, I tried to give an Alert() to see if it was running but not this.

Code that generates the fields:

$('#user_country').change(function () {
    if (this.value == 'Brazil') {
        if (!$('#user_cep').length) {
            $('#user_zip').remove();
            let input_cep = '<input type="text" placeholder="CEP" name="user_cep" id="user_cep" maxlength="8">';
            $('#user_country').after(input_cep);
        }
    } else if (this.value == 'France') {
        if (!$('#user_zip').length) {
            $('#user_cep').remove();
            let input_zip = '<input type="text" placeholder="ZIP" name="user_zip" id="user_zip" maxlength="5"/>';
            $('#user_country').after(input_zip);
        }
    } else {
        $('#user_cep').remove();
        $('#user_zip').remove();
    }
});

This part is OK, it is adding the fields on the screen correctly, but when consulting it is not working.

Test with VIACEP that does not work, does not perform anything

    $('#user_cep').blur(function () {
    let cep = $(this).val().replace(/\D/g, '');
    if (cep != "") {
        let validacep = /^[0-9]{8}$/;
        if (validacep.test(cep)) {
            $("#user_city").val("...");
            $("#user_state").val("...");
            $.getJSON("https://viacep.com.br/ws/" + cep + "/json/?callback=?", function (dados) {
                if (!("erro" in dados)) {
                    $("#user_city").val(dados.localidade);
                    $("#user_state").val(dados.uf);
                }
                else {
                    alert("CEP não encontrado.");
                }
            });
        }
        else {
            alert("Formato de CEP inválido.");
        }
    }
});

He just doesn’t fit in.

  • 1

    Hello William! See if it solves. It would be: $(document).on('blur', '#user_cep', function () {

  • In my case it would look like this. $(document).on("blur", '#user_cep', function () { ???

  • Now executed. You did not query the API but at least you have already entered the function.

  • That’s the way. Abs! ;)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.