Phone Mask using jQuery Mask Plugin

34

I need to change the position of the "-" in the mask.

<label for="telefone" >Telefone</label>
<input style="width:25%; margin-right:25% " type="tel" name="telefone" id="telefone" pattern="\([0-9]{2}\)[\s][0-9]{4}-[0-9]{4,5}" />
<script>$("#telefone").mask("(00) 0000-00009");</script>

With this solution the result is the following for mobile phones "(99) 1234-12345" and for fixed (99) 1234-1234.

But I would like to leave for mobile phones "(99) 12345-1234" and "(99) 1234-1234".

    
asked by anonymous 28.11.2014 / 13:18

13 answers

43

You can do this:

jQuery("input.telefone")
        .mask("(99) 9999-9999?9")
        .focusout(function (event) {  
            var target, phone, element;  
            target = (event.currentTarget) ? event.currentTarget : event.srcElement;  
            phone = target.value.replace(/\D/g, '');
            element = $(target);  
            element.unmask();  
            if(phone.length > 10) {  
                element.mask("(99) 99999-999?9");  
            } else {  
                element.mask("(99) 9999-9999?9");  
            }  
        });
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
Telefone: <input type="text" class="telefone" />
    
28.11.2014 / 13:41
16

You can do this in blur , I do not see a better alternative. That is, do the following:

$('#fone').mask('(00) 0000-00009');
$('#fone').blur(function(event) {
   if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
      $('#fone').mask('(00) 00000-0009');
   } else {
      $('#fone').mask('(00) 0000-00009');
   }
});

Recently I had a problem with using multiple inputs on the same screen, $('.phone-mask') because the mask was not updated, because unmask saves the selector in a variable, and how should I remask only the current input so it did not work, ie my code that was:

$('.phone-mask').mask('(00) 0000-00009');
$('.phone-mask').blur(function(event) {
   if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
      $(this).mask('(00) 00000-0009');
   } else {
      $(this).mask('(00) 0000-00009');
   }
});

It did not work because the mask was not created with the this selector but with the .phone-mask selector, but if I reapplied the mask would apply to all of the onscreen inputs and I did not want this, so my code stayed like this:

$('.phone-mask').each(function(i, el){
   $('#'+el.id).mask("(00) 00000-0000");
})
function updateMask(event) {
    var $element = $('#'+this.id);
    $(this).off('blur');
    $element.unmask();
    if(this.value.replace(/\D/g, '').length > 10) {
        $element.mask("(00) 00000-0000");
    } else {
        $element.mask("(00) 0000-00009");
    }
    $(this).on('blur', updateMask);
}
$('.phone-mask').on('blur', updateMask);
    
28.11.2014 / 13:35
13

Another option to apply a mask to 8- or 9-digit phones dynamically is to use the jquery.inputmask plugin. .

Two masks are defined one to eight digits and one to nine digits, the one responsible for keeping the hyphen in the correct place (or moving it) is keepStatic:true (by default it is false) that makes the change only when the new one default is detected after the fourth character is entered.

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="view-source:https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $("#telefone").inputmask({
        mask: ["(99) 9999-9999", "(99) 99999-9999", ],
        keepStatic: true
      });
    });
  </script>
</head>

<body>
  <input type="text" id="telefone" name="telefone" />
</body>

</html>
    
10.02.2016 / 22:01
8

You can do this:

var SPMaskBehavior = function (val) {
    return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
spOptions = {
    onKeyPress: function(val, e, field, options) {
        field.mask(SPMaskBehavior.apply({}, arguments), options);
    }
};

$('#telefone').mask(SPMaskBehavior, spOptions);
    
29.08.2015 / 07:02
8

Much simpler my friends, follow my suggestion: I just needed this function:

1st - Define the default mask with the ninth digit option: (99) 9999-9999? 9

2º - Create an onChange event to modify the mask once the field is changed (in this case, the phone).

Remembering that we are dealing with a mask regarding the Masked Input Plugin plugin. Many confuse with other plugins and so the code does not work. link

<script type="text/javascript">
jQuery( function($){
    $(".maskFone").mask("(99) 9999-9999?9");
    $(".maskFone").blur(function(event) {
        if($(this).val().length == 15){
          $('.maskFone').mask('(99) 99999-999?9');
        } else {
          $('.maskFone').mask('(99) 9999-9999?9');
        }
    });
});

    
17.07.2016 / 03:36
7

I found a pure javascript called Vanilla Masker and hard to find.

Enter the code link

or below

function inputHandler(masks, max, event) {
	var c = event.target;
	var v = c.value.replace(/\D/g, '');
	var m = c.value.length > max ? 1 : 0;
	VMasker(c).unMask();
	VMasker(c).maskPattern(masks[m]);
	c.value = VMasker.toPattern(v, masks[m]);
}

var telMask = ['(99) 9999-99999', '(99) 99999-9999'];
var tel = document.querySelector('input[attrname=telephone1]');
VMasker(tel).maskPattern(telMask[0]);
tel.addEventListener('input', inputHandler.bind(undefined, telMask, 14), false);

var docMask = ['999.999.999-999', '99.999.999/9999-99'];
var doc = document.querySelector('#doc');
VMasker(doc).maskPattern(docMask[0]);
doc.addEventListener('input', inputHandler.bind(undefined, docMask, 14), false);
div {
  font-family: Arial;
  padding: 5px;
  margin-bottom: 10px;
}  
input {
  box-sizing: border-box;
  padding: 10px;
  border-radius: 5px;
  border-color: black;
  width: 250px;
  font-size: 1.3em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-masker/1.1.0/vanilla-masker.min.js"></script><!--SandroAlvares(NãoutilizejQuery&Javascriptpuro)--><div><labelfor="tel">Telefone</label>
<input attrname="telephone1" type="text">
<br><div>
<label for="doc">CPF/CNPJ</label>
<input id="doc" type="text">

Official Tutorial: link

He's Brazilian, Vanilla Congratulations!

    
19.07.2016 / 17:36
7

Near-atomic solution:

    $(".phone-mask").mask("(99) 9999-9999?9").on("focusout", function () {
        var len = this.value.replace(/\D/g, '').length;
        $(this).mask(len > 10 ? "(99) 99999-999?9" : "(99) 9999-9999?9");
    });
    
16.02.2017 / 17:18
5

According to the documentation:

var SPMaskBehavior = function (val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
},
spOptions = {
    onKeyPress: function(val, e, field, options) {
                      field.mask(SPMaskBehavior.apply({}, arguments), options);
                    }
};

$('#id_tel_1').mask(SPMaskBehavior, spOptions);

I tested it and it worked perfectly.

    
17.12.2016 / 12:14
3

You can do this by using regular expressions. Ex:

function mascaraTelefone(number) {
    var regex = /^(.{1,2})(.{4,5})(.{4})/g;
    var number = 'number';
    var subst = '($1)$2-$3 ';

    var resultado = str.replace(regex, subst);
}
    
17.08.2017 / 13:02
2

A better and easier solution

$("#telefone").inputmask({
    mask: ["(99) 9999-9999", "(99) 99999-9999", ],
    keepStatic: true
});

Using the link plugin

    
17.07.2018 / 21:42
1

That was the one that solved my problem. Thank you!

jQuery("input.telefone")
        .mask("(99) 9999-9999?9")
        .focusout(function (event) {  
            var target, phone, element;  
            target = (event.currentTarget) ? event.currentTarget : event.srcElement;  
            phone = target.value.replace(/\D/g, '');
            element = $(target);  
            element.unmask();  
            if(phone.length > 10) {  
                element.mask("(99) 99999-999?9");  
            } else {  
                element.mask("(99) 9999-9999?9");  
            }  
        });
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
Telefone: <input type="text" class="telefone" />
    
05.05.2018 / 03:03
0

For version v1.14.12 of the Jquery Mask plugin .

You can use the following solution: Being Z, the optional digit.

$(document).ready(function(){
    $('#telefone1').mask("+55 31 9999-9999Z", {
      translation: {
         'Z': {
            pattern: /[0-9]/, optional: true
         }
       }
    });

});
    
04.10.2017 / 16:45
0

I had problems with most of the current backups .. I was able to run the following script:

    jQuery('input.your-tel')
        .mask('(99) 99999-9999')
        .focusout(function (event) {
            let target, phone, element;
            target = (event.currentTarget) ? 
                     event.currentTarget : 
                     event.srcElement;
            phone = target.value.replace(/\D/g, '');
            element = jQuery(target);
            element.unmask();
            if (phone.length > 10) {
                element.mask("(99) 99999-9999");
            } else {
                element.mask("(99) 9999-99999");
            }
        });
    
25.05.2018 / 19:29