Aaron Mills
Aaron Mills

Reputation: 182

Formatting a phone number in a form using 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);
         });
});

Upvotes: 2

Views: 5135

Answers (1)

matthias_h
matthias_h

Reputation: 11416

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

Upvotes: 4

Related Questions