I have the field like below
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
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 = phone.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1-$2-$3-$4");
maxlength
$('#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" />
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 setmaxlength=11