Formatting a phone number in a form using jquery

僤鯓⒐⒋嵵緔 提交于 2020-01-06 02:40:10

问题


I am attempting to format a phone number in a form input field using jquery, not sure what I am doing wrong....

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

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

            var phone = $(this).text();
            phone = phoneFormat(phone);
            $(this).text(phone);
         });
});

回答1:


You have to change this

var phone = $(this).text();
phone = phoneFormat(phone);
$(this).text(phone);

to

var phone = $(this).val();
phone = phoneFormat(phone);
$(this).val(phone);

because the value of an input field is retrieved and set using val() instead of text().

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

  function phoneFormat() {
    phone = phone.replace(/[^0-9]/g, '');
    phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    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" />


来源:https://stackoverflow.com/questions/27805961/formatting-a-phone-number-in-a-form-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!