jQuery - Use two functions together

Asked

Viewed 1,005 times

5

I need the same method to be called in two events, that is, in the page load the data, and if the input value is changed load the code again.

($("#cpf_cnpj").load(function() or $("#cpf_cnpj").focusout(function()) {
     codigo
}

How is the correct way to do according to the illustration above?

  • .ready is only used in the context of document, better explain which events.

2 answers

3

How about

function myFunction () { /* codigo */ }

document.addEventListener('DOMContentLoaded', myFunction);
document.getElementById('cpf_cnpj').addEventListener('change', myFunction);

I put Handler on change, so it only fires when the user has changed the field and is out of it. If you want to shoot every time the user changes the field (even if he is still in it), you can switch to input; both are IE 9+.

Jsfiddle.

1


$(document).ready(function(){

    $("#cpf_cnpj").on('load blur',validaCpfCnpj);

    function validaCpfCnpj(){
       // Script
    }

});

It can be done like this:

1 - Create event independent function.

2 - Then call the functions you want by the method on. In this case when loading page and leaving focus.


Another way:

$(document).ready(function(){

    validaCpfCnpj();

    $("#cpf_cnpj").on('blur',validaCpfCnpj);

    function validaCpfCnpj(){
       // Script
    }

});

Ps: always take a look at the Inspect Element in Chrome or the browser you use to discover the presence of an error.

  • 1

    I did as you said and it did not work.

  • @Tiago, I edited my post. Try the other way.

  • 1

    Isn’t there a problem there in the order of the statements? A validaCpfCnpj don’t need to be in the Handler of .ready(). Besides, I think that change is a more appropriate event than blur.

  • Do the following, then @ctgPi: put an ideal answer.

Browser other questions tagged

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