Reputation: 3052
I want to format my <input id="phone_number" type="tel">
on keypress
The requirements of my input field are:
(123) 457-7890
This is my current code:
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"$1-$2-$3");
jQuery("#phone_number").val(number);
}
});
Problem: The problem with my code is that it is not able to limit length
of my input
Final Output
should look like (123) 457-7890
first 3 digits enclosed in a parentheses
Any help is greatly appreciated. Thanks
Upvotes: 0
Views: 140
Reputation: 2245
I guess this should give you what is needed. You were very close to the answer.
I have limited the length of <input>
using the maxlength
attribute and added parenthesis in your phone_value.replace()
function surrounding $1
.
jQuery("#phone_number").on("keypress", function(event) {
var reg = /[0-9]/g;
var key = String.fromCharCode(event.keyCode);
if(!reg.test(key)){
// return false if NOT number
return false;
} else {
// numbers only
var phone_value = jQuery("#phone_number").val();
var number = phone_value.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(number);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="phone_number" type="tel" maxlength="14">
Upvotes: 1