Masquerade Exchange using Jquery Mask Plugin? [duplicate]

3

I'm creating a web system and in this system there is the phone field, in this phone field, the user can put a 0800 or a conventional standard phone DDD-Suffix-Prefix.

It's okay, I was able to create it with a if , but when typing the second number it changes the mask if it is of the chosen pattern, so 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>
    
asked by anonymous 21.08.2017 / 03:11

1 answer

1

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

  

Blur Event

     

The blur event is triggered when a particular element loses focus,   which can occur if the user presses TAB, for example, on the   control or click on another region of the page that you also receive   focus.

     

Source: Code Line

Verify that the field is not empty and the first few 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><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>
    
21.08.2017 / 05:06