skip to Main Content

I’m trying to add a 0 for my phone number mask. I want user to see 0 and then type the rest of their telephone number. How can I do this with jQuery?

jQuery(function ($) {
   $("#phoneNumber").mask("9(999) 999-9999");
});

User needs to see 0 at first and can’t remove it.
For example, it has to be like 0(555) 555-5555. 0 already needs to be in there when user types the phone number.

2

Answers


  1. In case you have an input and have a number 0 in it and you want that the user can’t remove the 0 you can do something like this:

    $('#phoneNumber').on('keydown', function(key) {
      if (key.which == 8 && $(this).value.length === 1) {
        return false;
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
    
    <input type="text" id="phoneNumber" />

    Couldn’t test it but You can just don’t let him remove the first entry of the input field with an hardcoded value in html which is the 0 you want to stand first. You need to enhance this by don’t let him type before the 0 and you need to disable copy & paste for example. The 8 after key.which stands for the current pressed key integer value. Which is 8 on pressing backspace.

    Login or Signup to reply.
  2. You can use the workaround below

    'translation': {
        0: null
    }
    

    The idea is that you remove default behavior '0': {pattern: /d/} specified in plugin (you can reassign this pattern to any other number or letter if you need)

    After this, mask plugin just insert leading 0 if that missed.

    $(function() {
      // 'Basic Usage Examples'
      $('.phone').mask('0 (999) 999-9999', {
        'translation': {
          0: null
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
    <div>
      <div class="col">
        <label>Phone</label>
        <input type="text" class="phone" />
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search