使用jquery格式化表单中的电话号码 [英] Formatting a phone number in a form using jquery

查看:108
本文介绍了使用jquery格式化表单中的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jquery格式化表单输入字段中的电话号码,不知道我做错了什么....

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);
         });
});


推荐答案

你必须改变这个

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

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

因为输入字段的值是使用 val()检索和设置的而不是 text()

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" />

这篇关于使用jquery格式化表单中的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆