JavaScript on IE and Chrome? (It works on Firefox) - javascript

function ord(string) {
var str = string + '',
code = str.charCodeAt(0);
if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
var hi = code;
if (str.length === 1) {
return code; // This is just a high surrogate with no following low surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know }
var low = str.charCodeAt(1);
return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
}
if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate return code; // This is just a low surrogate with no preceding high surrogate, so we return its value;
// we could also throw an error as it is not a complete character, but someone may want to know
}
return code;
}
}
$(document).ready(function () {
var maxTxtNumber = 8;
var arrTxtNumber = new Array();
var txtvalues = new Array();
var arr = {};
$('.numericonly').keypress(function (e) {
var t = $(this).val();
var k = e.which;
delete arr[8];
if ((e.which >= 49 && e.which <= 55) || e.which == 8) {
if (e.which == 8) {
var s = new String(t);
s = s.charCodeAt(0);
delete arr[s];
}
if (arr[k]) {
e.preventDefault();
} else {
arr[k] = e.which;
}
} else {
e.preventDefault();
}
});
});
The code works on Firefox but not on IE and Chrome?

Other browsers use e.keyCode to tell you which key was pressed. Cross-browser:
var k = e.keyCode || e.which;
Also make sure you use k rather than repeating e.which every time.

All that code is not required. If you want to test that an input's value is only digits, then something like the following will do:
<input type="text" onblur="check(this);" ...>
function check(el) {
if (!isDigits(el.value)) {
alert('Hey!!\nThe element you just left should only contain digits');
}
}
function isDigits(s) {
return /^\d*$/.test(s);
}
It's much more friendly to give the user a hint about the format you require and wait until they either leave the control or submit the form before offering a warning about invalid values. You really don't care how the user gets to a valid value, just so long as it's valid when the form is submitted.
And you must validate on the server again.

I recommend running your code through a validator such as http://www.jslint.com/ to make sure that everything adheres to universal standards.

Related

Wrapping a word in a textarea that has a per-line character limit and a total-line-number limit

I implemented a previous answer given here, and now I need to automatically wrap the word around the line instead of always having to manually press the enter key. Any ideas? I'm having quite a bit of trouble with this.
Code:
jQuery('#gift-message-whole-message').on('keypress', function (event) {
var text = jQuery('#gift-message-whole-message').val();
var lines = text.split('\n');
var currentLine = this.value.substr(0, this.selectionStart).split('\n').length;
if (event.keyCode == 13) {
if (lines.length >= jQuery(this).attr('rows')) return false;
} else {
if (lines[currentLine - 1].length >= jQuery(this).attr('cols')) {
return false;
}
}
});
Here is the working fiddle for your case.
I slightly changed the else branch as follows:
if (lines[currentLine - 1].length >= ($(this).attr('cols') - 1)) {
$('textarea').val($('textarea').val() + "-\n");
// return false; // prevent characters from appearing
}
As you can see in the fiddle, code adds a - and a new line, when typed text reaches to col limit. Then it goes on on the next line as user types.

Validate date on keypress not working

This is the regex :
pattern =/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
Hi guys, I found a simple regex for date format , no checking for leap year, but on my fiddle I can still input other invalid characters.
Please see my FIDDLE.
http://jsbin.com/ruhaxo/9/edit
Your code made me a little uncomfortable, so I tried to write this more simply so that it would be easier to read, you can pull out the part that you need, which I really think is just the event.preventDefault() when there is a match. Just to expand, as well: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes you are looking for char codes not the literal numbers.
$('input').on('keypress', function (e) {
var leng = $(this).val().length;
if (window.event) {
code = e.keyCode;
}else {
code = e.which;
};
var allowedCharacters = [49,50,51,52,53,54,55,56,57,48,45];
var isValidInput = false;
for (var i = allowedCharacters.length - 1; i >= 0; i--) {
if(allowedCharacters[i] == code){
isValidInput = true;
}
};
if(isValidInput === false || /* Can only input 1,2,3,4,5,6,7,8,9 or - */
(code == 45 && (leng < 2 || leng > 5 || leng == 3 || leng == 4)) ||
((leng == 2 || leng == 5) && code !== 45) || /* only can hit a - for 3rd pos. */
leng == 10 ) /* only want 10 characters "12-45-7890" */
{
event.preventDefault();
return;
}
});
You can also do this with an object, rather than an Array. Which is a little easier to read:
$('input').on('keypress', function (e) {
var leng = $(this).val().length;
if (window.event) {
code = e.keyCode;
}else {
code = e.which;
};
var allowedCharacters = {49:1,50:2,51:3,52:4,53:5,54:6,55:7,56:8,57:9,48:0,45:'-'}; /* KeyCodes for 1,2,3,4,5,6,7,8,9,- */
if(typeof allowedCharacters[code] === 'undefined'|| /* Can only input 1,2,3,4,5,6,7,8,9 or - */
(code == 45 && (leng < 2 || leng > 5 || leng == 3 || leng == 4)) ||
((leng == 2 || leng == 5) && code !== 45) || /* only can hit a - for 3rd pos. */
leng == 10 ) /* only want 10 characters "12-45-7890" */
{
event.preventDefault();
return;
}
});
EDITED:
Please be careful with this, I haven't fully tested this, but I edited the regex from the post mentioned, if you have this in addition to one of the other choices above, (this happens on keyup after the other checks have been made) this would validate the date in the format mm-dd-yyyy please check that it works properly, I tried 02-29-2008, the first leap year I could think of, and it worked, but I would recommend testing it more since it has been modified.
$('input').on('keyup',function(e){
/* From:
http://stackoverflow.com/questions/17503043/javascript-regular-expression-to-validate-date-in-mm-dd-yyyy-format
and
http://jsfiddle.net/LSsMc/
*/
var thisVal = $(this).val();
var leng = thisVal.length;
var reg = new RegExp(/^(((0[13578]|1[02])\-(0[1-9]|[12]\d|3[01])\-((19|[2-9]\d)\d{2}))|((0[13456789]|1[012])\-(0[1-9]|[12]\d|30)\-((19|[2-9]\d)\d{2}))|(02\-(0[1-9]|1\d|2[0-8])\-((19|[2-9]\d)\d{2}))|(02\-29\-((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if(leng == 10){
if(reg.test(thisVal)){
console.log('Valid Date');
}else {
event.preventDefault();
return;
}
}
});

Scroll if any alphanumeric character or symbol is pressed

I am writing a JS code that scrolls a container is any alphanumeric character or symbol is pressed.
This is what I came up with:
var $q = $('input#q');
$q.on('keydown', function (e) {
var reMatch = /[!-~]/.exec(e.which);
if (typeof reMatch != 'null' && reMatch.length > 0) {
$('#container').animate({scrollTop: 410}, 500);
$(this).off('keydown');
}
}).focus();
But this executes for all keys like shift, tab, enter etc ...
What's wrong with the code?
e.which gives a numeric representation of the key pressed. The number keys are represented by 48-57 (or 96-105 on the keypad) while letters are represented by 65-90
Try this:
var $q = $('input#q');
$q.on('keydown', function (e) {
var val = e.which;
var num = (val > 47 && val < 58 || val > 95 && val < 106);
var letter = (val > 64 && val < 91);
if (num || letter) {
$('#container').animate({scrollTop: 410}, 500);
$(this).off('keydown');
}
}).focus();
You could do this for it to work with anything that creates an input in the text field:
var $q = $('input#q');
$q.on('input', function (e) {
$('#container').animate({
scrollTop: 410
}, 500);
$(this).off('input');
}).focus();
but this will not work for IE versions less than 9. Although if you look, you can find shims. Here is an example
You could do this, but it would not scroll immediately if the user is holding a key down for a long time (until the user releases the key).
var $q = $('input#q');
var qval = $q.val()
$q.on('keyup', function (e) {
if(qval != $q.val()) {
$('#container').animate({scrollTop: 410}, 500);
$(this).off('keyup');
}
}).focus();

Restricting input box to numbers only, number keypad keys do not work [duplicate]

This question already has answers here:
keyCode values for numeric keypad?
(13 answers)
Closed 9 years ago.
I need your help,
The javascript coding works flawlessly and achieves the desired result, but for some reason, it does not allow the keys on the number pad to typed into the input box. Most users would type in numbers using the numlock keys on the keyboard. How can the coding be modified so as to allow the keys on the seperate number pad on the keyboard to function?
<!DOCTYPE html>
<html>
<body>
<div>
<input type="text" id="rownum">
</div>
<script type="text/javascript">
document.getElementById('rownum').onkeydown = function(e) {
var key = (window.event) ? event.keyCode : event.which;
alert(key);
if (key == 8) { // Delete key
return
}
else {
if ( isNaN( String.fromCharCode(key) ) ) return false;
}
}
</script>
</body>
</html>
The numbers in the numberpad have different keyCodes. Other keys like delete have the same keyCode in the normal keyboard and the numberpad, but the keyCode 8 (the one you have in your code) is for backspace, not Delete.
The sample code does not appear to be valid. I run it and get 'event is undefined'. This code works:
document.getElementById('rownum').onkeydown = function(e) {
var key = e.keyCode || e.which; // <-- updated reference to event
alert(key);
if (key == 8) { // Delete key
return
}
else {
if ( isNaN( String.fromCharCode(key) ) ) return false;
}
};
But as #Portnoy said, you will likely need to handle different keyCodes.
Proving that the array.indexOf(array) is supported:
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
then you can apply the following:
document.getElementById('rownum').onkeydown = function(e) {
var key = (window.event) ? event.keyCode : event.which;
var keys = [8,37,39,46,96,97,98,99,100,101,102,103,104,105]
var x = (keys.indexOf(key) > -1)
if (x != true) {
if (isNaN(String.fromCharCode(key))) { return false }
}
}

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