Mask input when loading page

Asked

Viewed 680 times

2

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

Follows the 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?

1 answer

1


You can take your object on onload and call the function as below:

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

Thus remaining:

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 set up, which is very complex for what you want to do.

This is well used: https://igorescobar.github.io/jQuery-Mask-Plugin/

Browser other questions tagged

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