问题
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