Changing Mask using Jquery Mask Plugin?

Asked

Viewed 378 times

3

I am creating a Web system and in this system there is the phone field, in this phone field, the user can put an 0800 or else a standard conventional phone DDD-Suffix-Prefix.

Even all right, I managed to create with a if, only that when typing the second number it changes the mask if it is of the chosen pattern, then in case I wanted to hold the pattern only for the first character.

Below is the code I created.

<input type="text" id="telefone" 
   name="escTelefone" 
   class="medio" 
   placeholder="(99)1111-1111" maxlength="13" />

<!--pattern="\([0-9]{2}\)[0-9]{4}-[0-9]{4}"-->
<script type="text/javascript">
    $("#telefone").keypress(function (event) { 
        if(event.keyCode == 48 ) { 
            $("#telefone").mask("0000-000-0000"); 
        } else { 
            $("#telefone").mask("(00)0000-0000");
        }       
    }); 
</script>

1 answer

1

Instead of using the event keypress, you can use the event Blur:

Blur event

The Blur event is triggered when a given element loses focus, what may occur if the user presses TAB, for example, on the control or click on another region of the page that also receives focus.

Source: Code line

Check that the field is not empty and what the first digits it contains.

$(document).on('blur', '#telefone', function(event) {
  var campo = $(this).val();
  // Verifica quais os primeiros dígitos informados.
  if (campo !== "" && campo.substring(0,2) === "08" || campo.substring(0,3) === "(08") {
    $("#telefone").mask("0000-000-0000");
  } else {
    $("#telefone").mask("(00) 0000-0000");
  }
  // console.log(campo.substring(0, 2));
});
<input type="text" id="telefone" name="escTelefone" class="medio" placeholder="(99)1111-1111" maxlength="13"  />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>

Browser other questions tagged

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