Input mask when loading page

2

I have a page that displays some user information. One of the fields is the telephone field. I want to apply a mask in this field when loading the page. I can even put the mask on, but only on the onKeyUp event. The problem is that the mask only appears when I press any key, and I need the mask to be applied as soon as I load the page.

Follow JS.

        <!-- Script para máscara de telefone -->
    <script type="text/javascript">

        /* Máscaras ER */
        function mascara( o, f ){
            v_obj = o
            v_fun = f
            setTimeout( "execmascara()", 1 )
        }

        function execmascara(){
            v_obj.value = v_fun( v_obj.value )
        }

        function mtel( v ){
            v = v.replace( /\D/g, "" );                  // Remove tudo o que não é dígito
            v = v.replace( /^(\d{2})(\d)/g, "($1) $2" ); // Coloca parênteses em volta dos dois primeiros dígitos
            v = v.replace( /(\d)(\d{4})$/, "$1-$2" );    // Coloca hífen entre o quarto e o quinto dígitos

            return v;
        }

        function id( el ){
            return document.getElementById( el );
        }

        window.onload = function(){
            id( 'txt-telefone' ).onkeyup = function(){
                                                mascara( this, mtel );
                                            }
        }
    </script>

How do I make the mask appear when loading the page?

    
asked by anonymous 21.08.2017 / 02:18

1 answer

1

You can get your object onload and call the function, as below:

var obj = document.getElementById("txt-telefone");
mascara(obj, mtel );

Looking like this:

window.onload = function(){
  var obj = document.getElementById("txt-telefone");
  mascara(obj, mtel);

  id( 'txt-telefone' ).onkeyup = function(){
    mascara( this, mtel);
  }
}

Tip:

There are frameworks that are easier to work with than the way you have set up, which is very complex for what you want to do.

This is well used: link

    
21.08.2017 / 04:15