我需要一个jquery解决方案,在用户输入类型时预先填充输入框的值。 例如,如果用户正在添加电话号码,如1234567890 我需要它自动将文本更改为(123)456-7890作为用户输入,我有什么办法可以使用jquery吗?
答案 0 :(得分:1)
尝试this,
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});