three button keyCode hotkey javascript - javascript

From another stackoverflow post (How can I add a JavaScript keyboard shortcut to an existing JavaScript Function?) I have this hotkey code:
function doc_keyPress(e) {
if (e.shiftKey && e.keyCode == 80) {
//do something
}
}
document.addEventListener('keyup', doc_keyPress, false);
which works with two keys. But with three keys, shift + l + m for example, it does not work.
the if statement would be:
if (e.shiftKey && e.keyCode == 76 && e.keyCode == 77) {}
again this does not work.
How do I get this working for shift + l + m.

tricky, tricky, but I managed to get it working. Just be aware that browsers have their own hot keys (like chromes [ctrl]+[shift]+i) which may override the function.
<!DOCTYPE html>
<html>
<body>
<input id="myInput" onkeydown="keyDownEvent(event)" onkeyup="resetKeys()">
</body>
</html>
<script>
var key1Pressed=false;
var key2Pressed=false;
function resetKeys(){
key1Pressed=false;
key2Pressed=false;
}
function keyDownEvent(e){
e=e||event, chrCode=(typeof e.which=="number")?e.which:e.keyCode;
if (e.shiftKey && chrCode === 76) key1Pressed=true;
if (e.shiftKey && chrCode === 77) key2Pressed=true;
if(key1Pressed && key2Pressed){
alert('Three Keys Are Pressed');
key1Pressed=false;
key2Pressed=false;
}
}
document.getElementById('myInput').focus();
</script>

Using a closure, I would envisage you can do something like this
var doc_keypress = (function() {
var prevWasL = false;
return function(e) {
if (e.type == 'keypress') {
if (e.shiftKey && !(e.ctrlKey || e.metaKey)) {
if (prevWasL) {
if (e.charCode == 77) {
console.log('doing it');
prevWasL = false;
return;
}
}
if (e.charCode == 76) {
prevWasL = true;
return;
}
}
prevWasL = false;
} else { // keyup
if (e.key == 'Shift') {
prevWasL = false;
}
}
}
}());
document.addEventListener('keypress', doc_keypress);
document.addEventListener('keyup', doc_keypress);
Add both keypress AND keyup event listeners so that the scenario of
Shift + L, release both, Shift + M, doesn't trigger a false positive
This would require shift then L then M being pressed in that order ... if you want either order of L and M, then the code would be a little different, but you should be able to figure that out
NOTE: I use charCode, because firefox at least, keyCode is always 0 on keyPress event

If you're trying to double press or triple press keys and catch an event after this, I've written a simple helper:
function KeyPress(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
KeyPress.prototype.bubbledReset = function bubbledReset(keyCode) {
var self = this;
if (this.opts.timeouts[keyCode]) {
clearTimeout(this.opts.timeouts[keyCode]);
this.opts.timeouts[keyCode] = 0;
}
this.opts.timeouts[keyCode] = setTimeout(function () {
self.opts.counts[keyCode] = 0;
}, this.opts.timeBetweenPresses);
};
KeyPress.prototype.onTap = function onTap(cb) {
var self = this;
return function handler(event) {
self.opts.counts[event.keyCode] = self.opts.counts[event.keyCode] || 0;
self.opts.counts[event.keyCode]++;
self.bubbledReset(event.keyCode);
cb(event.keyCode, self.opts.counts[event.keyCode]);
};
};
Usage
Simply use the onTap method to instance:
var keyPress = new KeyPress();
document.addEventListener('keyup', keyPress.onTap(function (keyCode, count) {
if (keyCode === 68 && count === 3) {
// 68 was tapped 3 times (D key)
}
if (keyCode === 13 && count === 6) {
// 13 was tapped 6 times (ENTER key)
}
}));
Hope this helps someone else!
Or if you prefer es6:
class KeyPress {
constructor(_opts) {
this.opts = Object.assign({}, {
counts: {},
timeouts: {},
timeBetweenPresses: 300
}, _opts || {});
}
bubbledReset(keyCode) {
if (this.timeouts[keyCode]) {
clearTimeout(this.timeouts[keyCode]);
this.timeouts[keyCode] = 0;
}
this.timeouts[keyCode] = setTimeout(() => {
this.counts[keyCode] = 0;
}, this.timeBetweenPresses);
}
onTap(cb) {
return event => {
this.counts[event.keyCode] = this.counts[event.keyCode] || 0;
this.counts[event.keyCode]++;
this.bubbledReset(event.keyCode);
cb(event.keyCode, this.counts[event.keyCode]);
};
}
}

Related

I want to perform different operation processes alternately in order with the same key operation

For example, you can start with a specific key and stop with a click or another key,
// Alt + Shift + ↓ Auto scroll
document.addEventListener("DOMContentLoaded", (l) => {
var m;
setInterval(m);
$(window).keydown((e) => {
//pattern 1
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
$(document).on('click', () => {
clearInterval(m);
m = undefined;
});
//pattern 2
setInterval(m);
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
if (e.keyCode == 96) { //ten key of「0」key
clearInterval(m);
m = undefined;
}
//}, false);
});
});
like this:
Attempting to process start and stop with the same key will not work.
In the example below
Start with Alt + Shift + ↓,
Stop as well
I want to do it with Alt + Shift + ↓. How can I correct it to implement the desired function?
The operating environment uses a third-party extension of the Chrome WEB store.
if i have understood what you want, you want to use the same keys to start and stop so, to do that you have to use a sort of toggle:
var timer;
var last_state = "keyup";
var param = 10;
$(window).on("keydown keyup", (e) => {
if (e.type == "keyup" && e.which == 40) {
last_state = "keyup";
}
if (e.type == "keydown" && e.type != last_state && e.altKey && e.shiftKey && e.which == 40) {
last_state = e.type;
if (!timer) {
timer = setInterval(() => {
scrollBy(0, param || 1);
}, 35);
} else {
clearInterval(timer);
timer = undefined;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Move player javascript

I do not understand this part :
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
explain what this code does, please)
MVC :
Controller:
this.init = function() {
keys = {};
}
self.trgt = function(){
if(this.event.target === myContainer.querySelector('#start')) {
myModel.startGame();
window.addEventListener('keydown', self.keyDown);
window.addEventListener('keyup', self.keyUp);
}
}
self.keyDown = function() {
keys[event.keyCode] = 1;
};
self.keyUp = function() {
delete (keys[event.keyCode]);
};
self.moveHero = function(keycode) {
myModel.moveHero(keycode);
};
setInterval(function() {
for (let keycode in keys) {
self.move(keycode);
}
}, 20);
Model:
if (!sometask) {
if (keycode == 37 || keycode == 65) {
self.moveLeft();
}
if (keycode == 38 || keycode == 87) {
self.moveTop();
}
if (keycode == 39 || keycode == 68) {
self.moveRight();
}
if (keycode == 40 || keycode == 83) {
self.moveBottom();
}
}
};
the code in question:
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
is just assigning which keys are currently pressed. Lets say event.keyCode = 37, In this instance your keys variable, which is an object, will now have a property that says keys[37] = 1, and it will remain that way until the keyUp function is called, deleting it. Whiile keys[37] = 1, the character will continue moving left, and this will stop once that key is deleted.
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
Translating to plain English:
If the user press the keyDown (number 40) then set the key 40 in the object keys to 1.
If the user press the keyUp (number 38) then delete from the keys object the key 38
These lines are to set functions that will be called each time the event keyDown (press a key) or keyUp (release the key) are called.
So let's focus on the actual code inside the function :
for keyDown, it sets a variable in a dictionary to a value. for instance, if you press down 'a', 'a' key on the keyboard has some int value which is 65 (see https://keycode.info/), and it will set the keys[65] = 1.
As long as you keep the button press, this value will stay, but as soon as you release it, the value is unset by using delete .
And so on for each keyboard key.
Then the main loop of the game will look which variables are set (by using "for ... in keys), and will execute a move function for each variable that has a special values, corresponding, I guess, to a-w-s-d or left-up-right-down.

javascript function is not executing

I have a checkbox. If I checks it, it will select all results:
HTML:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)" />
And Javascript:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
checkboxes = document.getElementsByName('id[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
var id = checkboxes[i].id;
var res = id.replace("checkbox", "tr");
if(source.checked)
{
$('#' + res + '').addClass('selected');
} else {
$('#' + res + '').removeClass('selected');
}
}
}
Now I am trying to select all results if I click CTRL+A on my keyboard. Here is my JavaScript:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
toggle();
}
}
});
But this function is not works. How can I make ctrl + a to select all results
The toggle function requires an argument or nothing. When no argument is passed the argument itself can be got directly from the dom. In the html the toggle function get the this keyword. The element itself is passed. But if no argument is passed the argument is undefined and so it can be computed dynamically:
<input type="checkbox" id="selectallcheckbox" onClick="toggle(this)"/>
In the toggle function try to change from:
function toggle(source = false) {
if(!source)
{
var source = document.getElementById('selectallcheckbox');
}
...........
to:
function toggle(source) {
if (source === undefined) {
source = document.getElementById('selectallcheckbox');
}
and, finally, in your jQuery(document).keydown(function(e) { change to:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
// get the argument to the toggle function
var eleObj = document.getElementById('selectallcheckbox');
// toggle the checkbox status
eleObj.checked = !eleObj.checked;
// call the toggle function with the correct argument
toggle(eleObj);
}
}
});
I found solution:
jQuery(document).keydown(function(e) {
if (e.ctrlKey) {
if (e.keyCode == 65 || e.keyCode == 97) { // 'A' or 'a'
e.preventDefault();
document.getElementById("selectallcheckbox").click();
}
}
});

Call function based on input

I've an textbox in asp.net,when i enter ";" semicolon in textbox means it have to call a function.Is there any way to do this.please help me out guys..i tried change function but it calls at every keypress in textbox.
$('#prgrp').on('change', function (evt)
{
var txt = $("#prgrp").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
var duplicateValues = [];
for (var i = 0; i < valueSortArray.length; i++)
{
if (valueSortArray[i + 1] == valueSortArray[i])
{
duplicateValues.push(valueSortArray[i]);
}
}
if (duplicateValues.length > 0)
{
$("#duplicate").html("Don't enter repeated values");
$('#duplicate').css('color', 'RED');
$("#prgrp").autocomplete("disable");
}
else {
$("#duplicate").html("");
$("#prgrp").autocomplete("enable");
}
});
Try this:-
$("#prgrp").keypress(function (e) {
if (e.keyCode == 59) {
//Call your function here
}
});
Please note, you can also use e.which in place of e.keyCode as it is jquery standardized.
Try this
$('#prgrp').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code == 59) { //
//Do something
}
});
Demo
try this code
$( "#prgrp" ).keypress(function( event ) {
if ( event.which == 59 || event.keycode == 59 ) {
//your function call
}
});

input field, only numbers jquery/js

I have a input field where i only wish users to type numbers
html: <input id="num" type="text" name="page" size="4" value="" />
jquery/ js:
$("#num").keypress(function (e){
if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
return false;
}
});
hope someone can help me.
btw: I'm not interesting in a larger jquery plugin to make the function work. (I have found some jquery-plugins , but there must be som other ways to fix it, with a smaller code)
Try this:
$("#num").keypress(function (e){
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
});
Values 48 through 57 represent the digits 0-9.
Never do this. A user can update a textbox without pressing the key. He can copy paste, drag. some text.
Also this will be irritating to the user.
Just display a label nect to the filed saying that this accepts only numbers. And then
Validate your code at submission
Comparing to the current best answer this code is more user-friendly - it allows usage of arrows, backspace, delete and other keys/combinations:
// Ensures that it is a number and stops the key press
$('input[name="number"]').keydown(function(event) {
if (!(!event.shiftKey //Disallow: any Shift+digit combination
&& !(event.keyCode < 48 || event.keyCode > 57) //Disallow: everything but digits
|| !(event.keyCode < 96 || event.keyCode > 105) //Allow: numeric pad digits
|| event.keyCode == 46 // Allow: delete
|| event.keyCode == 8 // Allow: backspace
|| event.keyCode == 9 // Allow: tab
|| event.keyCode == 27 // Allow: escape
|| (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+A
|| (event.keyCode == 67 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+C
//Uncommenting the next line allows Ctrl+V usage, but requires additional code from you to disallow pasting non-numeric symbols
//|| (event.keyCode == 86 && (event.ctrlKey === true || event.metaKey === true)) // Allow: Ctrl+Vpasting
|| (event.keyCode >= 35 && event.keyCode <= 39) // Allow: Home, End
)) {
event.preventDefault();
}
});
Notes:
The event.metaKey === true is required for Mac users (thanks RyanM for noticing this).
Also if you uncomment Ctrl+V sequence you will need to write additional code for checking pasted text (disallow non-numeric symbols).
Here is my solution:
function InputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
throw ('Please specify a valid input');
if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
throw 'Please specify a valid Validation type';
input.InputValidator = this;
input.InputValidator.ValidCodes = [];
input.InputValidator.ValidCodes.Add = function (item) {
this[this.length] = item;
};
input.InputValidator.ValidCodes.hasValue = function (value, target) {
var i;
for (i = 0; i < this.length; i++) {
if (typeof (target) === 'undefined') {
if (this[i] === value)
return true;
}
else {
if (this[i][target] === value)
return true;
}
}
return false;
};
var commandKeys = {
'backspace': 8,
'tab': 9,
'enter': 13,
'shift': 16,
'ctrl': 17,
'alt': 18,
'pause/break': 19,
'caps lock': 20,
'escape': 27,
'page up': 33,
'page down': 34,
'end': 35,
'home': 36,
'left arrow': 37,
'up arrow': 38,
'right arrow': 39,
'down arrow': 40,
'insert': 45,
'delete': 46,
'left window key': 91,
'right window key': 92,
'select key': 93,
/*creates Confusion in IE */
//'f1': 112,
//'f2': 113,
//'f3': 114,
//'f4': 115,
//'f5': 116,
//'f6': 117,
//'f7': 118,
//'f8': 119,
//'f9': 120,
//'f10': 121,
//'f11': 122,
//'f12': 123,
'num lock': 144,
'scroll lock': 145,
};
commandKeys.hasValue = function (value) {
for (var a in this) {
if (this[a] === value)
return true;
}
return false;
};
function getCharCodes(arrTarget, chars) {
for (var i = 0; i < chars.length; i++) {
arrTarget.Add(chars[i].charCodeAt(0));
}
}
function triggerEvent(name, element) {
if (document.createEventObject) {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on' + name, evt)
}
else {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(name, true, true); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
if (validationType == InputValidator.ValidationType.Custom) {
if (typeof (validChars) === 'undefined')
throw 'Please add valid characters';
getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}
input.InputValidator.ValidateChar = function (c) {
return this.ValidCodes.hasValue(c.charCodeAt(0));
}
input.InputValidator.ValidateString = function (s) {
var arr = s.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
}
}
return arr.join('');
}
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
function getCaretPosition(i) {
if (!i) return;
if ('selectionStart' in i) {
return i.selectionStart;
}
else {
if (document.selection) {
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -i.value.length);
return sel.text.length - selLen;
}
}
}
function setCursor(node, pos) {
var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;
if (!node) {
return false;
}
else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}
return false;
}
function validateActive() {
if (input.isActive) {
var pos = getCaretPosition(input);
var arr = input.value.split('');
for (var i = 0; i < arr.length; i++) {
if (!this.ValidateChar(arr[i])) {
arr[i] = '';
if (pos > i)
pos--;
}
}
console.log('before : ' + input.value);
input.value = arr.join('');
console.log('after : ' + input.value, input);
setCursor(input, pos);
setTimeout(validateActive, 10);
}
}
bindEvent(input, 'keypress', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});
bindEvent(input, 'keyup', function (e) {
var evt = e || window.event;
var charCode = evt.which || evt.keyCode;
if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
}
});
bindEvent(input, 'change', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
if (input.value !== dt)
triggerEvent('change', input);
});
bindEvent(input, 'blur', function (e) {
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
input.isActive = false;
if (input.value !== dt)
triggerEvent('blur', input);
});
bindEvent(input, 'paste', function (e) {
var evt = e || window.event;
var svt = input.value;
if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
if (/text\/html/.test(evt.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/html');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else if (/text\/plain/.test(e.clipboardData.types)) {
var dt = evt.clipboardData.getData('text/plain');
input.value = input.InputValidator.ValidateString(dt);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
input.value = '';
}
waitforpastedata(input, svt);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
input.value = '';
waitforpastedata(input, svt);
return true;
}
});
bindEvent(input, 'select', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
bindEvent(input, 'selectstart', function (e) {
var evt = e || window.event;
if (evt.preventDefault) {
evt.preventDefault();
evt.stopPropagation();
}
return false;
});
/* no need to validate wile active,
removing F keys fixed IE compatability*/
//bindEvent(input, 'fucus', function (e) {
// input.isActive = true;
// validateActive();
//});
//validate current value of the textbox
{
var dt = input.value;
input.value = input.InputValidator.ValidateString(input.value);
//trigger event to indicate value has changed
if (input.value !== dt)
triggerEvent('change', input);
}
function waitforpastedata(elem, savedcontent) {
if (elem.value !== '') {
var dt = input.value;
elem.value = elem.InputValidator.ValidateString(elem.value);
if (input.value !== dt)
triggerEvent('change', input);
}
else {
var that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself, 10);
}
}
}
InputValidator.ValidationType = new (function (types) {
for (var i = 0; i < types.length; i++) {
this[types[i]] = types[i];
}
})(['Numeric', 'Custom', 'Decimal']);
To apply it to an input, do the following :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Decimal);/* Numeric or Custom */
If you specify Custom as the validation type you have to specify the valid characters.
eg :
new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');
Here's my code:
$("Input.onlyNumbersInput").live('input', function (event) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
Using "live('input')" event will make the function replace any character that is not a digit, which the user input, WITHOUT the user see the character.
If you use "onkeyup" event, the user will see the character for few miliseconds, which is not cool.
This works for me:
$(document).ready(function () {
$(".onlyNumbersInput").on('keyup keydown blur', function (event) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
});
It's based on #luizfelippe answer, updated for jquery 1.7+
This code allows paste and will remove any non numeric character in realtime.
I think you forgot putting e.preventDefault(); before return.
This is how I do it:
jQuery( '#input').keyup(function() {
var value = jQuery(this).val();
var newValue = value.replace(/\D/g,''); //remove letters
newValue = parseInt(newValue);
jQuery(this).val(newValue);
value = jQuery(this).val();
//just as safety, if some weird character is in the input
if( isNaN (value) || value == "" ){
jQuery(this).val(0);
}
}
The keyup event seems just fine for me to do this, I've also tried keypress and keydown.
My JQuery Solution.
const validKeyCodes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
$('#your_input').on('keypress', function(e) {
return validKeyCodes.indexOf(e.keyCode) > -1
})
text input:
<input id="number" type="text" />
and script:
var number = $('#number');
number.on('input', function () {
$(this).val(getOnlyNumbers($(this).val()));
});
// this function return only numbers as string or ''
function getOnlyNumbers(value) {
let arr = value.toString().split('');
let number = [];
arr.forEach(function (elem) {
let charCode = elem.charCodeAt(0);
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
} else {
number.push(elem);
}
});
return parseInt(number.join('')) || '';
}
KeyCodes or charCodes is not the best way to do this if you use numbers above letters in your laptop and don't have normal keyboard connected. And if you know these numbers above letters, starting with key `(~) , were used to add specific symbols of different nations language. So only numbers will become numbers and letters. For example: key 1(!) - in Lithuanian language is ą .
So better way is to use this var newValue = value.replace(/\D/g,'');
This taken from answer above.
Try this Script:
var str = 5.5;
str = str.toString();
var errnum = [];
var onlyNumbers = [0,1,2,3,4,5,6,7,8,9,"0","1","2","3","4","5","6","7","8","9"];
for(i = 0; i < str.length; i++) {
if(jQuery.inArray(str[i],onlyNumbers) == -1){
errnum.push(str[i]);
}
}
if(errnum.length >= 1){
console.log('not numeric character found!');
}

Categories