Javascript switch - javascript

I am working on a zodiac calendar that requires a switch 0-11 for the signs. I have written HTML code that drops down for the month and a text input for the year. The sign should use id 'output' and should also show up in text. I am not sure if I am using my switch correctly, of if my math is causing the problem or why it is not sending to output.
HTML CODE:
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
Javascript Code
if (year && year.value && (year.length == 4)){
year = parseInt(years.value);
month = parseInt(month.value);
if (month < 2) {
year = (year - 1);
}
year = ((year - 1924) % 12);
} else { // Show Error:
document.getElementById('year').value =
'Please enter valid values.';
}
switch (year){
case 0 :
block code;
break;
etc..
} // End Switch
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
return false;
}

Your regular expression could be failing to match your lowercased url. When that happens, the result would be null.
You should be checking the match() result before using it. Something like this:
var matches = url.toLowerCase().match(/https?:\/\/(.+?)[?#\/$]/);
if (!matches || matches.length < 2) {
// Handle error
...
} else {
// Keep going
var domain = matches[1];
...
}
Also, verify that your regular expression is actually doing what you intend.

Because of my javascript code innerText
if (output.textContent != undefined) {
output.textContent = sign;
} else {
output.innerText = sign;
}
I had to delete
<div><label for="sign">Sign</label><input type="text"
name ="sign" id="sign"></div>
and replace it with
<p>Sign: <span id="output"></span></p>
I could have easily changed the javascript code and document.getElementID('output') = sign.value;

The problem should be caused by domain checking instead of calculate function.
Remove domain checking and try again (see if it works).
Errors:
1) if (year && year.value && (year.value.length == 4)){
year = parseInt(year.value);
2) main html didn't declare element "output"

Related

Parameter comparing won't work

Everything works just fine - everything except this one if-else-statement:
else if ((day = 0 || day = 6) && (hour <= 19)) {
greeting = "We wish you a nice weekend and a nice " +
Weekdays[day] + ".";
}
Firefox's Error Message: 'ReferenceError: invalid assignment left-hand side'
..it should be really easy but till now I coudn't find the problem.
Thanks for helping and have a nice day!
Use == for comparison(by value) and = for assigning values.
So in your case, it should be:
...
else if ((day == 0 || day == 6) && (hour <= 19)) {
greeting = "We wish you a nice weekend and a nice " +
Weekdays[day] + ".";
}
...
If you need to compare by both type and value, you should use ===
In short:
var a = 10; // assigns value 10 to variable `a`
"1"==1 // true => Since == compares by value
"1"===1 // false => Since === compares by both type and value. In this case although value is 1, both are of different types (string and integer)

i want to validate date in javascript.can anyone help me in understandin this? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
var dcheck=/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;
can anyone one help me in understanding this part
"/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/;/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\{4}$/"
....can u please tell me how this checks the input also?
if(dcheck.test(dor)){
document.getElementById('div_id').innerHTML="Correct Entry";
}
else{
document.getElementById('div_id').innerHTML="please check ";
}
Thanks In Advance!!!
/^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-{4}$/ is a regular expression, commonly used to match strings of various forms. Let's step through it bit by bit to figure out what it's doing.
/^(0?[1-9]|[12][0-9]|3[01])-:
Here, we check if the string starts with a certain two-digit string. The vertical bar here means or, so either we match 0?[1-9], [12][0-9], or 3[01]. The first means "It's a single digit day, and we don't care if you start with 0 or not." The "we don't care" is encoded by a question mark. The second is for a two-digit day where the second digit is unrestricted, and the third is saying that the date, if starting with 3, must be either 30 or 31. Finally, the - just means we end in a -, for this section.
(0?[1-9]|1[012])-:
Here, we do something similar. This part is of the form 0?[1-9] or 1[012]. Hopefully you can see, by referring to the previous paragraph, that this accepts months from 1 to 12, where single digits may start with a 0.
{4}
This is a new symbol we haven't seen. {n} just means "Accept an n-digit string".
So what we end up with is "Day-Month-Year", where the parentheses capture the day, month, and year, and stick them into variables.
Hope that helped!
Html Code:
<form name="frmSample" method="post" action="" onSubmit="return ValidateForm()">
<p>Enter a Date <font color="#CC0000"><b>(mm/dd/yyyy)</b></font>
:
<input type="text" name="txtDate" maxlength="10" size="15">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
javascript Code:
<script language = "Javascript">
/**
* DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/datevalidation.asp)
*/
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strMonth=dtStr.substring(0,pos1)
var strDay=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr=strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : mm/dd/yyyy")
return false
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month")
return false
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day")
return false
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
return false
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
alert("Please enter a valid date")
return false
}
return true
}
function ValidateForm(){
var dt=document.frmSample.txtDate
if (isDate(dt.value)==false){
dt.focus()
return false
}
return true
}
</script>
try this one. it may helpful to you.

determining var type from prompt command and if else statement

I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/

Check whether white spaces exist without using trim

I have following code that checks whether date is valid. http://jsfiddle.net/uzSU6/36/
If there is blank spaces in date part, month part or year part the date should be considered invalid. For this, currently I am checking the length of string before and after trim operation. It works fine. However is there a better method to check for white spaces? (For example, using === operator)
function isValidDate(s)
{
var bits = s.split('/');
//Javascript month starts at zero
var d = new Date(bits[2], bits[0] - 1, bits[1]);
if ( isNaN( Number(bits[2]) ) )
{
//Year is not valid number
return false;
}
if ( Number(bits[2]) < 1 )
{
//Year should be greater than zero
return false;
}
//If there is unwanted blank space, return false
if ( ( bits[2].length != $.trim(bits[2]).length ) ||
( bits[1].length != $.trim(bits[1]).length ) ||
( bits[0].length != $.trim(bits[0]).length ) )
{
return false;
}
//1. Check whether the year is a Number
//2. Check whether the date parts are eqaul to original date components
//3. Check whether d is valid
return d && ( (d.getMonth() + 1) == bits[0]) && (d.getDate() == Number(bits[1]) );
}
You can use indexOf() function if there is space in the date string.
if(s.indexOf(' ') != -1)
{
//space exists
}
you can test for any whitespace like
if( /\s/g.test(s) )
it will test any whitespace.
You may want to consider using a regexp to test your string's validity:
function isValidDate(s) {
var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var mdy = s.match(re);
if (!mdy) {
return false; // string syntax invalid;
}
var d = new Date(mdy[3], mdy[1] - 1, mdy[2]);
return (d.getFullYear() == mdy[3]) &&
(d.getMonth() == mdy[1] - 1) &&
(d.getDate() == mdy[2]);
}
The regex does all this in one go:
checks that there are three fields separated by slashes
requires that the fields be numbers
allows day and month to be 1 or 2 digits, but requires 4 for the year
ensures that nothing else in the string is legal
See http://jsfiddle.net/alnitak/pk4wU/

How to format a phone number with jQuery

I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:
<p class="phone">2124771000</p>
Simple: http://jsfiddle.net/Xxk3F/3/
$('.phone').text(function(i, text) {
return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});
Or: http://jsfiddle.net/Xxk3F/1/
$('.phone').text(function(i, text) {
return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});
Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.
var phone = '2124771000',
formatted = phone.substr(0, 3) + '-' + phone.substr(3, 3) + '-' + phone.substr(6,4)
Don't forget to ensure you are working with purely integers.
var separator = '-';
$( ".phone" ).text( function( i, DATA ) {
DATA
.replace( /[^\d]/g, '' )
.replace( /(\d{3})(\d{3})(\d{4})/, '$1' + separator + '$2' + separator + '$3' );
return DATA;
});
Here's a combination of some of these answers. This can be used for input fields. Deals with phone numbers that are 7 and 10 digits long.
// Used to format phone number
function phoneFormatter() {
$('.phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '')
if (number.length == 7) {
number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
}
$(this).val(number)
});
}
Live example: JSFiddle
I know this doesn't directly answer the question, but when I was looking up answers this was one of the first pages I found. So this answer is for anyone searching for something similar to what I was searching for.
Use a library to handle phone number. Libphonenumber by Google is your best bet.
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');
// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414
I recommend to use this package by seegno.
try something like this..
jQuery.validator.addMethod("phoneValidate", function(number, element) {
number = number.replace(/\s+/g, "");
return this.optional(element) || number.length > 9 &&
number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
$("#myform").validate({
rules: {
field: {
required: true,
phoneValidate: true
}
}
});
I have provided jsfiddle link for you to format US phone numbers as
(XXX) XXX-XXX
$('.class-name').on('keypress', function(e) {
var key = e.charCode || e.keyCode || 0;
var phone = $(this);
if (phone.val().length === 0) {
phone.val(phone.val() + '(');
}
// 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() + '-');
}
if (phone.val().length >= 14) {
phone.val(phone.val().slice(0, 13));
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.on('focus', 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
}
})
.on('blur', function() {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
Live example: JSFiddle
Quick roll your own code:
Here is a solution modified from Cruz Nunez's solution above.
// Used to format phone number
function phoneFormatter() {
$('.phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '')
if (number.length < 7) {
number = number.replace(/(\d{0,3})(\d{0,3})/, "($1) $2");
} else if (number.length <= 10) {
number = number.replace(/(\d{3})(\d{3})(\d{1,4})/, "($1) $2-$3");
} else {
// ignore additional digits
number = number.replace(/(\d{3})(\d{1,3})(\d{1,4})(\d.*)/, "($1) $2-$3");
}
$(this).val(number)
});
};
$(phoneFormatter);
JSFiddle
In this solution, the formatting is applied no matter how many digits the user has entered. (In Nunes' solution, the formatting is applied only when exactly 7 or 10 digits has been entered.)
It requires the zip code for a 10-digit US phone number to be entered.
Both solutions, however, editing already entered digits is problematic, as typed digits always get added to the end.
I recommend, instead, the robust jQuery Mask Plugin code, mentioned below:
Recommend jQuery Mask Plugin
I recommend using jQuery Mask Plugin (page has live examples), on github.
These links have minimal explanations on how to use:
https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/
http://www.igorescobar.com/blog/2012/05/06/masks-with-jquery-mask-plugin/
http://www.igorescobar.com/blog/2013/04/30/using-jquery-mask-plugin-with-zepto-js/
CDN
Instead of installing/hosting the code, you can also add a link to a CDN of the script
CDN Link for jQuery Mask Plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
or
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
WordPress Contact Form 7: use Masks Form Fields plugin
If you are using Contact Form 7 plugin on a WordPress site, the easiest option to control form fields is if you can simply add a class to your input field to take care of it for you.
Masks Form Fields plugin is one option that makes this easy to do.
I like this option, as, Internally, it embeds a minimized version of the code from jQuery Mask Plugin mentioned above.
Example usage on a Contact Form 7 form:
<label> Your Phone Number (required)
[tel* customer-phone class:phone_us minlength:14 placeholder "(555) 555-5555"]
</label>
The important part here is class:phone_us.
Note that if you use minlength/maxlength, the length must include the mask characters, in addition to the digits.
Consider libphonenumber-js (https://github.com/halt-hammerzeit/libphonenumber-js) which is a smaller version of the full and famous libphonenumber.
Quick and dirty example:
$(".phone-format").keyup(function() {
// Don't reformat backspace/delete so correcting mistakes is easier
if (event.keyCode != 46 && event.keyCode != 8) {
var val_old = $(this).val();
var newString = new libphonenumber.asYouType('US').input(val_old);
$(this).focus().val('').val(newString);
}
});
(If you do use a regex to avoid a library download, avoid reformat on backspace/delete will make it easier to correct typos.)
An alternative solution:
function numberWithSpaces(value, pattern) {
var i = 0,
phone = value.toString();
return pattern.replace(/#/g, _ => phone[i++]);
}
console.log(numberWithSpaces('2124771000', '###-###-####'));
$(".phoneString").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return text;
});
Output :-(123) 657-8963
I found this question while googling for a way to auto-format phone numbers via a jQuery plugin. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.
Problem
I would like my phone number html input field to auto-format (mask) the value as the user types.
Solution
Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.
Formatting a phone number is as easy as:
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});
Input:
4546644645
Code:
PhoneNumber = Input.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "($1)$2-$3");
OutPut:
(454)664-4645
Following event handler should do the needful:
$('[name=mobilePhone]').on('keyup', function(e){
var enteredNumberStr=this.$('[name=mobilePhone]').val(),
//Filter only numbers from the input
cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
inputLength=cleanedStr.length,
formattedNumber=cleanedStr;
if(inputLength>3 && inputLength<7) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
}else if (inputLength>=7 && inputLength<10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}else if(inputLength>=10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}
console.log(formattedNumber);
this.$('[name=mobilePhone]').val(formattedNumber);
});
To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.
$('#phone').on('input', function() {
var number = $(this).val().replace(/[^\d]/g, '');
if (number.length == 3) {
number = number.replace(/(\d{3})/, "$1-");
} else if (number.length == 4) {
number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
} else if (number.length == 5) {
number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
} else if (number.length == 6) {
number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
} else if (number.length == 7) {
number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
} else if (number.length == 8) {
number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
} else if (number.length == 9) {
number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
} else if (number.length == 10) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
} else if (number.length == 11) {
number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
} else if (number.length == 12) {
number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
}
$(this).val(number);
});
may be this will help
var countryCode = +91;
var phone=1234567890;
phone=phone.split('').reverse().join('');//0987654321
var formatPhone=phone.substring(0,4)+'-';//0987-
phone=phone.replace(phone.substring(0,4),'');//654321
while(phone.length>0){
formatPhone=formatPhone+phone.substring(0,3)+'-';
phone=phone.replace(phone.substring(0,3),'');
}
formatPhone=countryCode+formatPhone.split('').reverse().join('');
you will get +91-123-456-7890

Categories