Mask.js:5 Uncaught Typeerror: v_fun is not a Function

Asked

Viewed 122 times

-1

I am using a JS script to customize masks on inputs within forms. A file mask.js is being loaded into the pages, containing the following functions:

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout(() => {
        v_obj.value=v_fun(v_obj.value)
    },1)        
}
function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v

}

An input:

<div class="col-sm-2">
    <div class="form-group">
        <label for="cep">CEP do Endereço</label>
        <input type="text" class="form-control cep" id="cep" name="cep" 
         placeholder="00.000-000" required>
    </div>
</div>

And a script at the bottom of the page to relate input to function:

$('.cep').attr("onkeypress", "mascara(this, cep)")
$('.cep').attr("maxlength", "9")

But I get the bug:

"Uncaught Typeerror: v_fun is not a Function at Mask.js:5",

being line 5:

v_obj.value=v_fun(v_obj.value)

I can’t find the error. The interesting thing is that the same script works on another page perfectly. When using the console.log(v_fun) within the function mascara, on the page that works correctly the return is:

f cep(v){
v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
return v

But on the page that does not work the return is equal to the html component that called it:

<input type="text" class="form-control cep" id="cep" name="cep" placeholder="00.000-000" required="" onkeypress="mascara(this, cep)" maxlength="9">
  • Try renaming the function and passing the parameter to aplicarCEP

  • Could you give me a clear example of what it would look like?

  • I really don’t see any clearer way to say

  • @Sorack I managed to solve with your solution, THANK YOU!!

1 answer

0


The problem is that when you relate cep in the onkeypress, the browser interprets as input with the id cep.

Change the function cep for aplicarMascaraCEP:

...
function aplicarMascaraCEP(v){
...

And the call:

...
$('.cep').attr("onkeypress", "mascara(this, aplicarMascaraCEP)")
...
  • That was exactly the problem

Browser other questions tagged

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