I want to format my <input id="phone_number" type="tel"> on keypress
The requirements of my input field are:
numbers only and no letters and other special characters
format the input field with a US number like (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
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">
Related
In below snippet code, If i give inputs "9999999999" and "9999999999." in console log both displays the same result "999999999" with out dot.
Am trying to capture dot symbol even after number. Here, only input type number is allowed cannot use text or any other type.
Text box is for number
Number: <input type='number' id=txtNumber'/>
And it's javascript function
$(document).ready(function() {
$('#txtNumber').keyup(function () {
var numbers = $(this).val(); console.log("numbers", numbers);
});
});
code at JSFiddle
Please help to find solution.
The reason is you set type='number'.
I suggest you set type='text' and use regular expressions to check if the value in the input is a number(include dot) or not:
$(document).ready(function() {
$('#txtNumber').keyup(function () {
if ($(this).val().match(/^[0-9]*\.?[0-9]*$/)){ //check if your value is number or not
var numbers = $(this).val(); console.log("numbers", numbers);
}
});
});
You can use a function to do this:
$(document).ready(function () {
$('#txtNumber').keyup(function () {
var numbers = $(this).val(); console.log("numbers", numbers);
// dump(numbers);
numbers = parseInt(numbers).toFixed(2);
console.log(numbers);
});
});
It will give you your desired output.
I need javascript to format a telephone number as it is typed. This would replace all non-numeric characters and insert dashes if the user doesn't type them in. So far this is the closest I've gotten, but it is thrown off if they put a dash in the wrong spot. The ideal solution would be to replace dashes only in the wrong spots. I was looking for a way to possibly replace the 4th and the 8th digit differently but haven't come up with a solution.
$('#TelephoneNo').keyup(function (ev) {
if (/[^0-9\-]/g.test(this.value))
{
this.value = this.value.replace(/[^0-9\-]/g, '');
}
if (/^(\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
});
Assuming you want the format "123-456-7890":
function formatPhoneNumber(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3];
}
<html>
<head>
<script type="text/javascript">
function CheckNum(ev) {
var inputval=document.getElementById("TelephoneNo").value;
debugger
if(inputval){
if (/[^0-9\-]/g.test(inputval))
{
inputval = inputval.replace(/[^0-9\-]/g, '');
}
if(detectPosition()){
if (/^(\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
}
document.getElementById("TelephoneNo").value=inputval;
}
}
function detectPosition() { var inputval=document.getElementById("TelephoneNo").value;
if(inputval.indexOf("-") ==4 || inputval.indexOf("-") ==8)
{
return 1;
}
return -1;
}
</script>
</head>
<body>
<input type="text" id="TelephoneNo" onkeyup="CheckNum(this)">
</body>
</html>
I know this is an old question, but I figured I might help someone out.
I did this xxx-xxx-xxxx as-you-type formatting using two cases: one for formatting where the length required one hyphen, and another for formatting with two required. That way, the last group always expects an unknown char count and doesn't wait until the end of the user input to enforce the format.
function formatPhone() {
var element = document.getElementById('phone');
var inputValue = element.value;
// length < 3 : no formatting necessary
if (inputValue.length > 3 && inputValue.length < 8)
// length < 8 : only one hyphen necessary, after first group of 3
// replace (remove) non-digits, then format groups 1 and 2
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{0,3})/g, '$1-$2');
else
// length >= 8 : 2 hyphens required, after first two groups of 3
// replace (remove) non-digits, then format groups 1, 2, and 3
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{3})(.{0,4})/g, '$1-$2-$3');
element.value = result;
}
Type a phone number, it will be formatted to xxx-xxx-xxxx as you type:<br/><br/>
<input type="text" id="phone" maxlength="12" onkeyup="formatPhone()"></input>
I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.
I was taking the approach of using jQuery.keydown, and checking what the key was and using.
input numbers max length 999.999
-
my result after . (point) 3 number it is goog. but 99999.999
I need 999.999,222.222,22.01 ->
max length +++.+++
this my code
<input type="text" id="spinEdit2" class="aSpinEdit" />
<script type="text/javascript">
var txt = document.getElementById('spinEdit2');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?|[0-9])/g;
val = re1.exec(val);
//console.log(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
</script>
Thanks
How about
/^([0-9]{1,3}(?:\.[0-9]{0,3})?)/g
In case you want the details: the {1,3} means the preceding thing can happen from 1 to 3 times. The (?:) is a non-captured group -- it's a grouping of the following symbols, but it doesn't capture to any variables like $1.
I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you
Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}
Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.
I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);