Jquery: change input text value on focusout

1.2k Views Asked by At

I have the field like below

enter image description here

input text is fixed to 11 digit.

Now When focus out I want the input text to be changed like below

123-456-789-01

how can I achive this using Jquery

can anyone guide me

1

There are 1 best solutions below

0
Hien Nguyen On BEST ANSWER

You can use regex below to format your phone phone = phone.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1-$2-$3-$4"); and set maxlength=11

$('#phone').focusout(function() {

  function phoneFormat() {
    phone = phone.replace(/[^0-9]/g, '');
    phone = phone.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1-$2-$3-$4");
    return phone;
  }
  var phone = $(this).val();
  phone = phoneFormat(phone);
  $(this).val(phone);
});

$('#phone').focusout(function() {

  function phoneFormat() {
    phone = phone.replace(/[^0-9]/g, '');
    phone = phone.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1-$2-$3-$4");
    return phone;
  }
  var phone = $(this).val();
  phone = phoneFormat(phone);
  $(this).val(phone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="text" value="" id="phone" maxlength="11"  />