Run Ajax script automatically

0

I have a problem with a college project.

I would like to know how to run this Ajax script automatically:

<script type="text/javascript">
function buscaCep() {
    var cep = $( "#cep" ).val();

    var infos = {
        'iCep': cep
    };

    $.ajax( {
        crossDomain: true,
        type: "POST",
        url: "",
        data: infos
    } ).done( function ( data ) {
        var json = $.parseJSON( data );
        $( "#log" ).val( json.lograd );
        $( "#cidade" ).val( json.cidade );
        $( "#bairro" ).val( json.bairro );
        $( "#estado" ).val( json.estado );
    } );
}

After the user completes an input:

<input type="text" name="cep" id="cep" onkeyup="maskIt(this,event,'#####-###')"/>

    
asked by anonymous 16.04.2018 / 17:18

3 answers

2

If I understand you want to execute after filling in the "correct format" , ie if wrong fill (including the mask) should check the contents of what was typed

In case you use onfocusout or onblur it can only conflict with the runtime of the mask, for example if you entered wrong and focus the field the ajax would execute anyway, so to avoid this you can use a regex with .test() in string , like this:

<input type="text" name="cep" id="cep" onkeyup="maskIt(this,event,'#####-###')" onblur="buscaCep()"/>

And in JS like this:

function buscaCep() {
    var cep = $( "#cep" ).val();

    //Se o formato for inválido ele executa o "return"
    if (!/^\d{5}-\d{3}$/.test(cep)) return;

    var infos = {
        'iCep': cep
    };

    $.ajax( {
        crossDomain: true,
        type: "POST",
        url: "",
        data: infos
    } ).done( function ( data ) {
        var json = $.parseJSON( data );
        $( "#log" ).val( json.lograd );
        $( "#cidade" ).val( json.cidade );
        $( "#bairro" ).val( json.bairro );
        $( "#estado" ).val( json.estado );
    } );
}

How regular expression works

A (regular expression) in the specific case works like this :

^\d{5}-\d{3}$
^ ^   ^     ^
. .   .     .
. .   .     ... Deve terminar exatamente com a expressão anterior
. .   .     
. .   ... Deve conter um hífen entre ambos números
. .
. ... \d indica que deve ser um numero e o {5} indica que deve
.      conter 5 numeros (no outro {3} indica que deve conter 3 numeros)
.
... Indica que deve começar exatamente com a proxima expressão
    
16.04.2018 / 17:34
1

You can use the event onblur in a similar way as you used onkeyup .

Example:

<input type="text" name="cep" id="cep" onkeyup="maskIt(this,event,'#####-###')" onblur="buscaCep()"/>

The onblur event is fired when the input field loses focus

    
16.04.2018 / 17:23
1

There are several possibilities in this case, one of them would be to use the onfocusout event, that is, after the user populate the field and focus the field, the function will be executed.

<input type="text" name="cep" id="cep" onkeyup="maskIt(this,event,'#####-###')" onfocusout="buscaCep()" />
    
16.04.2018 / 17:26