jQuery - Use two functions together

5

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

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

How is the correct way to do the above illustration?

    
asked by anonymous 23.06.2015 / 19:12

2 answers

1
$(document).ready(function(){

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

    function validaCpfCnpj(){
       // Script
    }

});

It can be done like this:

1 - Create the event-independent function.

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

Another way:

$(document).ready(function(){

    validaCpfCnpj();

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

    function validaCpfCnpj(){
       // Script
    }

});

Ps: Always take a look at Inspect Element in Chrome or the browser you use to find out if there is an error.

    
23.06.2015 / 19:21
3

How about

function myFunction () { /* codigo */ }

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

I put the handler in change , so it only fires when the user changed the field and left it. If you want to fire every time the user changes the field (even though it is still in it), you can trade for input ; both are IE 9+.

JSFiddle .

    
23.06.2015 / 20:13