Wrong execution on function in JS - javascript

I have this code, but somewhy when i use this function to validate my input field everything works, except + and - keys, even thought i noted them as true. What have i done wrong?
function validateNumber(event)
{
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 107 || event.keyCode == 109 ||
event.keyCode == 32 )
{
return true;
}
else if(key < 48 || key > 57)
{
return false;
}
else return true;
};

I don't see you checking for 189 (-) and 187 (=, which is really what happens when you type +). You might want to check if the Shift key is pressed for +.
As already noted, it's overall a wrong way to validate user input. You need to inspect the value of the input, not individual keystrokes.
First, define a validation function that would check an arbitrary text with a regexp:
function checkArithmetic(str) {
var regexp = /^[0-9+-]$/;
return regexp.test(str);
}
Next, add a handler to your input element:
input.addEventListener('input', function (e) {
var value = input.value;
if (checkArithmetic(value)) {
// OK!
} else {
// error
}
}, false);

Related

How to restrict apart from alphabets and numbers any other keys (function keys, shortcut keys etc.) press action on datatable search input?

Jquery:
Is there please an option to start the search only alphabet and number keys have been typed in?
Datatable globally searching should initiate at least with 3 characters
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user press enter (keycode = 13) on search we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
});
});
Solution:
Check this solution. I hope, it will work.
$(document).on('draw.dt','.dataTable', function() {
$(".dataTables_filter input").off().on("input keyup", function(e) {
// if value length is greater than 3 or user presses enter (keycode = 13) on search
// we will search on datatable
if(this.value.length >= 3 || e.keyCode == 13 || this.value == "") {
var checkBackspaceEnter = e.keyCode == 8 || e.keyCode == 13;
// if user removes a character from search we will search
var checkAlphabet = (e.keyCode >= 58 && e.keyCode <= 90);
// check on alphabets
var checkNum = (e.keyCode >= 48 && e.keyCode <= 57
|| e.keyCode >= 96 && e.keyCode <= 105);
// check on number values
var ctrlCombine = (e.keyCode == 17 || ((e.keyCode == 65 || e.keyCode == 67 )
&& e.ctrlKey));
// don't search when user hits Ctrl+A or Ctrl+C
checkAlphabet = ((ctrlCombine == false) ? checkAlphabet : false);
if (checkAlphabet || checkNum || checkBackspaceEnter) {
var dataTable = $('.table').DataTable();
dataTable.search(this.value).draw();
}
}
});
});
Use regular expressions with preg_replace to remove letters other than alpha-numeric on every keyup and then check the length of a string.
Hope you get the desired result.

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(
// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};
This is original code and it doesn't work on dynamic content
that is why i want to modify it!
How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
https://jsfiddle.net/daveSalomon/r5n8xuhx/6/
There's no JS required - just use a number input:
<input class="amount" type="number">

How to allow only defined characters as input using jQuery?

How do i allow special characters such as hyphen,comma,slash,space key,backspace key,delete key along with alphanumeric values and restrict the rest in jQuery?
As this criteria(allowed characters/input values) varies from field to field, i would like to make it as a utility method which accepts input field id and allowed characters as parameters.
for example: limitCharacters(textid, pattern)
​You can just check the keyCode on keydown and run preventDefault() if match:
$('input').keydown(function(e) {
if (e.which == 8) { // 8 is backspace
e.preventDefault();
}
});​
http://jsfiddle.net/GVb6L/
If you need to restrict to certain chars AND keyCodes + make it into a jQuery plugin, try something like:
$.fn.restrict = function( chars ) {
return this.keydown(function(e) {
var found = false, i = -1;
while(chars[++i] && !found) {
found = chars[i] == String.fromCharCode(e.which).toLowerCase() ||
chars[i] == e.which;
}
found || e.preventDefault();
});
};
$('input').restrict(['a',8,'b']);​
http://jsfiddle.net/DHCUg/
I did something like this but in jQuery plugin format. This example will only allow numbers and full stops.
You can call this by writing:
$("input").forceNumeric();
And the plugin:
jQuery.fn.forceNumeric = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}
I would suggest using David solution for modifier keys like backspace and delete and this code below for characters:
var chars = /[,\/\w]/i; // all valid characters
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
});
Also, I've experienced some problems with keydown so I'd do it on keyup.
Demo: http://jsfiddle.net/elclanrs/QjVGV/ (try typing a dot . or semicolon ;)

Is the shiftkey held down in JavaScript

I have written a JS function that only allow numbers to be entered. A copy of that function is below:
function NumbersOnly(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
//Allow tab, backspace and numbers to be pressed, otherwise return false for everything.
//(keyCode>=96 && keyCode<=105) are the numpad numbers
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
}
This function works fine with all the numbers but my problem happens when the shift key is held down and one of the number keys is pressed. The value returned is one of the characters above the numbers. So for example if I hold down shift and press 7, '&' is returned but the keyCode is still 55!! I would have expected that to be different.
So my question is how do I check if the shift key is being held down.
I've tried the following check but this didn't work:
if (keyCode === 16) {
evt.returnValue = false;
}
else {
if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105) || keyCode === 9 || keyCode === 8) {
}
else {
evt.returnValue = false;
}
}
I'm using ASP.NET 4.0.
Any help would be gratefully received.
Thanks in advance.
You can check if shift key is pressed using :
if(evt.shiftKey) {
... //returns true if shift key is pressed
Use event.key instead of charCode. No more magic numbers!
function onEvent(event) {
const key = event.key; // "a", "1", "Shift", etc.
if (isFinite(key)) { // Is number
// Do work
}
};
Mozilla Docs
Supported Browsers
use keypress for holding any key isntead of keydown

Detect numbers or letters with jQuery/JavaScript?

I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if (event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || ...) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) {
alert('input was 0-9');
}
if (event.keyCode >= 65 && event.keyCode <= 90) {
alert('input was a-z');
}
For a more dynamic check, use a regular expression:
const input = String.fromCharCode(event.keyCode);
if (/[a-zA-Z0-9-_ ]/.test(input)) {
alert('input was a letter, number, hyphen, underscore or space');
}
See the MDC documentation for the keyCode property, which explains the difference between that and the which property and which events they apply to.
Use event.key and modern JS!
No number codes anymore. You can check key directly.
const key = event.key.toLowerCase();
if (key.length !== 1) {
return;
}
const isLetter = (key >= 'a' && key <= 'z');
const isNumber = (key >= '0' && key <= '9');
if (isLetter || isNumber) {
// Do something
}
You could also use a simple regex. ^$ ensures 1 char, i ignores case
/^[a-z0-9]$/i.test(event.key)
or individually:
const isLetter = /^[a-z]$/i.test(event.key)
const isNumber = /^[0-9]$/i.test(event.key)
First, if you're doing this, make sure it's in the keypress event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
alert("Letter or number typed");
}
};
If you want to check for backspace, I'd use the keydown event instead and check for a keyCode of 8 because several browsers (including Chrome) do not fire a keypress event for the backspace key.
if (event.keyCode >= 48 && event.keyCode <= 90) {
// the key pressed was alphanumeric
}
For numeric values:
function validNumeric() {
var charCode = event.which ? event.which : event.keyCode;
var isNumber = charCode >= 48 && charCode <= 57;
if (isNumber) {
return true;
} else {
return false;
}
}
Here, 48 to 57 is the range of numeric values.
For alphabetic values:
function validAlphabetic() {
var charCode = event.which ? event.which : event.keyCode;
var isCapitalAlphabet = charCode >= 65 && charCode <= 90;
var isSmallAlphabet = charCode >= 97 && charCode <= 122;
if (isCapitalAlphabet || isSmallAlphabet) {
return true;
} else {
return false;
}
}
Here, 65 to 90 is the range for capital alphabets (A-Z), and
97 to 122 is the range for small alphabets (a-z).
As #Gibolt said, you should use event.key.
Because charCode, keyCode and which are being deprecated.
To detect letters & numbers when using <input> or <textarea> you can use input event.
This event fires when <input> or <textarea> value changes so there is no need to worry about keys like Alt, Shift, arrows etc. Even more - if you use mouse to cut part of the text the event fires as well.
var element = document.getElementById('search');
element.addEventListener('input',function(e){
console.log(element.value);
});
<input id="search" type="text" placeholder="Search" autocomplete="off">
Simply you can add your Html forms in the input field like this:
...onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"
You don't need any function. This Validation works only with the email field. Don't use naming or number. To use number, remove email regular expression like this:
...onkeypress ="return /[a-z ]/i.test(event.key)" required accesskey="4"
For number only:
...onkeypress ="return /[0-9]/i.test(event.key)" required accesskey="4"
Don't forget, to add for each input fields their own value.
<div class="form-group">
<input type="Email" class="form-control " id="EMAILADDRESS" name="EMAILADDRESS" placeholder="Email Address" autocomplete="false" onkeypress ="return /[a-z .# 0-9]/i.test(event.key)" required accesskey="4"/>
</div>
$('#phone').on('keydown', function(e) {
let key = e.charCode || e.keyCode || 0;
// 32 = space - border of visible and non visible characters - allows us to backspace and use arrows etc
// 127 - delete
if (key > 32 && (key < 48 || key > 58) && key !== 127) {
e.preventDefault();
return false;
}
});
modified answer of #user4584103, allows us to remove characters, and navigate in input box and filter out every not number character
You can also use charCode with onKeyPress event:
if (event.charCode > 57 || event.charCode < 48) {
itsNotANumber();
} else {
itsANumber();
}
number validation, works fine for me
$(document).ready(function () {
$('.TxtPhone').keypress(function (e) {
var key = e.charCode || e.keyCode || 0;
// only numbers
if (key < 48 || key > 58) {
return false;
}
});
});
Accept numbers or letters with JavaScript by Dynamic Process using regular expression.
Add onkeypress event for specific control
onkeypress="javascript:return isNumber(event)"
function numOnly(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
function Alphanum(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/[a-z0-9]/i.test(charStr)) {
return true;
} else {
return false;
}
}
Use $.isNumeric(value); return type is boolean
$(document).ready(function () {
return $.isNumeric(event.keyCode);
});
A very simple, but useful method to try (i needed on a keyup event, letters only),
use console.log() to check, typeOfKey is a string so you can compare. typeOfKey is either (Digit or Key)
let typeOfKey = e.code.slice(0,-1)
if(typeOfKey === 'Key'){
console.log(typeOfKey)
}

Categories

Resources