jqueryhtmljquery-mask

jQuery Mask plugin multiple masks for phone number on the same element doesn't work


I am using the jQuery Mask plugin and I used it before tons of times but now I have to do it for production release, I can't seem to mask a phone number input correctly, I can input (11) 1111-1111 without problem but it doesn't let me add another number, if I did add another number it should change the mask to (11) 1 1111-1111. That is the same example found on every website (including this one).

$().ready(() => {
  var moptions = {
    placeholder: "(__) ____-____",
    onKeyPress: function(cep, e, field, options) {
      var masks = ["(00) 0000-0000", "(00) 0 0000-0000"];
      var mask = cep.length > 14 ? masks[1] : masks[0];
      $(".phone").mask(mask, options);
    }
  };

  $(".phone").mask("(00) 0000-0000", moptions);
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<input type="text" class="phone"/>


Solution

  • The primary issue here is that you are attempting to detect the length of the string, however when you switch masks you are introducing two additional characters '0 ', which is throwing off the number of characters to use.

    You might consider ignoring non-digit characters which would give you a better idea of which mask to use such that the masks wouldn't interfere with your count using an example like the following:

    $().ready(() => {
      var maskOptions = {
        placeholder: "(__) ____-____",
        onKeyPress: function(cep, e, field, options) {
          // Use an optional digit (9) at the end to trigger the change
          var masks = ["(00) 0000-00009", "(00) 0 0000-0000"],
            digits = cep.replace(/[^0-9]/g, "").length,
            // When you receive a value for the optional parameter, then you need to swap
            // to the new format
            mask = digits <= 10 ? masks[0] : masks[1];
    
          $(".phone").mask(mask, options);
        }
      };
    
      $(".phone").mask("(00) 0000-0000", maskOptions);
    });
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
    <input type="text" class="phone" />