jQuery input mask for phone number

sean vitale picture sean vitale · Mar 31, 2017 · Viewed 26.3k times · Source

I want a user's input to autofill the punctuation of a phone number in order to look like this (xxx) xxx-xxxx. This is my HTML code:

  <div class="form-group">
    <label class="control-label col-sm-2">Phone Number:</label>
    <div class="col-sm-10">          
      <input type="text" class="form-control" name="phoneNumber"
           id="phoneNumber" value="<?php echo $row["phoneNumber"];?>">
    </div>
  </div>

What else do I need to do to complete this task? I am trying to use jQuery and an input mask.

Answer

Neil picture Neil · Mar 31, 2017

You can accomplish this by using the Input Mask jQuery extension.

$('#phoneNumber').inputmask("(999) 999-9999");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>

<label class="control-label col-sm-2">Phone Number:</label>
  <div class="col-sm-10">          
  <input type="text" class="form-control" name="phoneNumber" id="phoneNumber" value="">
</div>