issue with eventlistner keypress - javascript

I've an event listner so for some keys it does some thing different and so on, first if not working pressing "-" does not trigger the commands written but other two works perfectly!
second one submits as soon as entering Enter and third one denies anything other than numbers.
what could be the issue with first one?
document.querySelector(".header__input").addEventListener("keypress", function (evt) {
if (evt.keyCode === 109 || evt.which === 109 || evt.keyCode === 189 || evt.which === 189){
operation = "-";
alert("sucecss")
}
else if (evt.keyCode === 13 || evt.which === 13){
starter();
}
else if (evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});

I'm not sure exactly why you're having a problem on the subtract symbol. However, I should point out that keypress is deprecated. Mozilla docs
I suggest using keydown. Like this:
var x = document;
x.addEventListener('keydown', function (evt) {
if (evt.keyCode === 109 || evt.which === 109 || evt.keyCode === 189 || evt.which === 189) {
operation = "-";
alert("sucecss")
}
else if (evt.keyCode === 13 || evt.which === 13) {
starter();
}
else if (evt.which < 48 || evt.which > 57) {
evt.preventDefault();
}
})

doing some tweaking was able to fix the numpad issue with keydown.
thanks to jacob.
document.querySelector(".header__input").addEventListener("keydown", function (evt) {
if (evt.keyCode === 13 || evt.which === 13){
starter();
}
else if (evt.which < 48 || evt.which > 57 && event.which < 97){
evt.preventDefault();
}
else if (evt.which > 105){
if(evt.keyCode === 109 || evt.which === 109 || evt.keyCode === 189 || evt.which === 189){
operation = "-";
}
else{
evt.preventDefault();
}
}
});

Related

Disable all keys but copy paste combination

I am writing a code for number field where i have disabled all keys except number keys
function doValidation(event) {
var charCode = event.keyCode;
if (charCode != 190 && charCode != 40 && charCode != 39 && charCode != 38 && charCode != 37 && charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
return false;
}
<input type="text" onkeydown="doValidation(event)">
Now i want to enable ctrl+c and ctrl+v in this funtion.
you can do this like below :)
var is_ctrl_pressed = false;
$('#number_input').on('keydown', function(e) {
var code = e.which;
if ((code > 47 && code < 59) || (code > 95 && code < 106) || (is_ctrl_pressed && (code == 67 || code == 86))) {
return true;
} else if (code == 17) {
is_ctrl_pressed = true;
} else {
return false;
}
});
$('#number_input').on('keyup', function(e) {
if (e.which == 17) {
is_ctrl_pressed = false;
}
});
Hope this will be helpful.
$('input[type="number"]').keypress(function(e){
//Numbers 47 to 57 are the key code of digit 0 to 9.
if (![48,49,50,51,52,53,54,55,56,57].includes(e.keyCode)){
e.preventDefault();
}
});
// Disable Right click
document.addEventListener('contextmenu', event => event.preventDefault());
// Disable key down
document.onkeydown = disableSelectCopy;
// Disable mouse down
document.onmousedown = dMDown;
// Disable click
document.onclick = dOClick;
function dMDown(e) { return false; }
function dOClick() { return true; }
function disableSelectCopy(e) {
// current pressed key
var pressedKey = String.fromCharCode(e.keyCode).toLowerCase();
if ((e.ctrlKey && (pressedKey == "c" || pressedKey == "x" || pressedKey == "v" || pressedKey == "a" || pressedKey == "u")) || e.keyCode == 123) {
return false;
}
}

jquery clash: “right arrow” and “single quote” getting same keycode in keypress

Similar to this question but a bit different
Javascript keycode clash: "right arrow" and "single quote"
He is using javascript while I am using jquery.
I cannot use keydown event. I want to manage it in keypress event only.
I want to allow Right arrow(& other navigation keys) but disallow entering single quote. both are getting keycode 39.
$(document).ready(function () {
$(".InjectionSafe").keypress(InjectionSafe);
});
function InjectionSafe(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
console.log(charCode);
if (charCode === 9 || charCode == 8 || charCode == 46 // TAB , backspace, delet, left arrow and right arrow
|| charCode == 37 ) { //was pressed
return true;
}
//if (!(charCode != 222 && charCode != 188 && charCode != 190 && charCode!=39)) { // ' < >
if (!(charCode != 60 && charCode != 62 && charCode != 39)) { // ' < >
return false;
}
return true;
}
updated fiddle :https://jsfiddle.net/g2g0sbfo/
Type something & use navigation keys.
Update: I can confirm that this issue is only in firefox(My version is 59.0.1). IE, chrome & opera work fine.
I toyed around with Firefox to see what's happening.
Here is what I got :
You can check originalEvent.key to see which key was actually pressed.
If you pressed ', originalEvent.key = "'".
If you pressed the right arrow, originalEvent.key = "ArrowRight".
$(document).on('keypress', e => {
var charCode = e.which ? e.which : e.keyCode;
$('body').html(charCode);
if (charCode == 39) {
if (e.originalEvent.key == 'ArrowRight') { //Right arrow
$('body').append('<p>Right arrow</p>');
} else {
//Single quote
$('body').append('<p>Single quote</p>');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to get the character (.) full stop which is 190 on the keycode chart to be included in the allowable keys?

The code below works, but I am not able to get 190 as a part of the keys that can be allowed. The ultimate objective is to get the user to only be able to input (0-9) and a decimal point (.).
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (evt.which != 8 && evt.which != 0
&& (evt.which < 48 || evt.which > 57)
&& evt.charCode != 190) {
return false;
}
return true;
}
As you can see on this site http://www.asquare.net/javascript/tests/KeyCode.html the returned char code differs from onKeyDown, onKeyPress and onKeyUp.
EDIT:
Added working example of this with jquery, but it should be the same for javascripts nativ keypress event.
// with jQuery
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (evt.which != 8 && evt.which != 0
&& (evt.which < 48 || evt.which > 57)
&& evt.charCode != 46 // IMPORTANT keypress charCode 46 == ".", String.fromCharCode(46) -> "."
) {
return false;
}
return true;
}
$("input").keypress(function(e) {
if (isNumber(e)) {
result = "Is a number";
} else {
result = "Is not a number";
}
console.log(result);
$("#result").html(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<div id="result">result</div>

JavaScript keycode allow number and plus symbol only

I have this JavaScript function that is used to force user only type number in the textbox. Right now and I want to modify this function so it will allow the user to enter plus (+) symbol. How to achieve this?
//To only enable digit in the user input
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Since the '+' symbol's decimal ASCII code is 43, you can add it to your condition.
for example :
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
This way, the Plus symbol is allowed.
This code might work. I added support for SHIFT + (equal sign) and the numpad +.
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
var shiftPressed = (window.Event) ? e.modifiers & Event.SHIFT_MASK : e.shiftKey;
if ((shiftPressed && charCode == 187) || (charCode == 107))
{
return true;
} else if ((charCode > 95) && (charCode < 106)) {
return true;
} else if (charCode > 31 && (charCode < 48 || charCode > 57))) {
return false;
} else {
return true;
}
}
this is stupid ... not really an answer at all. I would suggest you to do following.
function isNumberKey(evt)
{
console.log(evt.keyCode);
return false;
}
And find out the ranges of all keys, and implement it.
It's Work. Javascript keycode allow number and plus symbol only
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation</title>
</head>
<body>
<form name="form1" action="#">
Mobile Number: <input type='text' id='PhoneNumber' maxlength="10" onKeyPress="return IsNumeric3(event);" ondrop="return false;" onpaste="return false;"/>
<span id="error3" style="color: Red; display: none">* Input digits (0 - 9)</span>
</form>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8);
specialKeys.push(43);
specialKeys.push(37);
specialKeys.push(39);
//Backspace
function IsNumeric3(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = (keyCode != 37 && keyCode != 8 && keyCode != 46 && (keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error3").style.display = ret ? "none" : "inline";
return ret;
}
</script>
<script>
function stringlength(inputtxt, minlength, maxlength)
{
var field = inputtxt.value;
var mnlen = minlength;
var mxlen = maxlength;
if(field.length<mnlen || field.length> mxlen)
{
alert("Please input the 10 digit mobile number");
return false;
}
else
{
return true;
}
}
</script>
</body>
</html>
Thank you friends
Here is the modified code:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if ( (charCode >= 48 && charCode <= 57) || charCode == 43)
return true;
return false;
}
Here is the code . working fine with numbers and plus + sign in phone fields. you will have to implement the code on keydown function . target the id/class of the particular phone field and use keydown function.
//allows only these keys
// backspace, delete, tab, escape, and enter
if ( event.keyCode == 107 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
Using experience of my colleagues above, write one function, that fits me well. It filters all except numbers, arrows and backspace. Maybe it would be useful for somebody.
function isKeyCorrect(keyEvent) {
var charCode = keyEvent.which ? keyEvent.which : keyEvent.keyCode;
var isNotNumber = charCode < 48 || charCode > 57;
var isNotArrow = charCode < 37 || charCode > 40;
var isNotBackspace = charCode !== 8;
return isNotNumber && isNotArrow && isNotBackspace;
}
<script type="text/javascript">
$(document).ready(function() {
`enter code here` $('#form-1').submit(function(msg) {
$.post("action.php?act=login",$(this).serialize(),function(data){
if (data == 'ERR:A3001004') { alert("Güvenlik hatası, sayfayı yenileyin."); }
else if (data == 'TIMEEND') { alert("Anahtarınızın süresi dolmuş."); }
else if (data == 'INVALID') { alert("Geçersiz anahtar şifresi girdiniz."); }
else if (data == 'OK') { alert("Başarıyla giriş yaptınız. Yetişkinlere göre içerik barındıran sitelere erişim sağlayabilirsiniz."); }
});
return false;
});
});
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>

javascript : key validation

im using javascript to validate keys in textbox. it is not working :(
function numeric(e) {
return ((e.keyCode == 8) ||
(e.keyCode == 9) ||
(e.keyCode > 47 && e.keyCode < 58) ||
(e.keyCode > 36 && e.keyCode < 41) ||
(e.keyCode == 46) ||
(e.keyCode > 95 && e.keyCode < 106) ||
e.keyCode == 190 ||
e.keyCode == 110);
}
help me...
function numeric(e) {
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode === 13){
alert("cheese");
}
}
I know that in I.E. you can set event.keyCode=0 to suppress the key appearing in the control. But I think you need to trap the onkeydown. Firefox might have an equivalent. This is good because it prevents the key actually "arriving" at the control.
Also keep in mind that you might need to handle combinations of Shift + key and alt + key.
a good debug technique for this sort of thing is to say windows.status = event.keyCode,
and you can see what the keycode is as you type it...
Just try out the following code. I have checked F5 keycode, you can check as you want
function disableKey(event)
{
if (!event) event = window.event;
if (!event) return;
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if (keyCode == 116) {
showMsg("This functionality is disabled.");
window.status = "F5 key detected! Attempting to disabling default response.";
window.setTimeout("window.status='';", 2000);
// Standard DOM (Mozilla):
if (event.preventDefault) event.preventDefault();
//IE (exclude Opera with !event.preventDefault):
if (document.all && event && !event.preventDefault) {
event.cancelBubble = true;
event.returnValue = false;
event.keyCode = 0;
}
return false;
}
}
function setEventListenerForFrame(eventListener)
{
document.getElementById('your_textbox').onkeydown = eventListener;
//frames['frame'].document.onkeypress = eventListener;
}
<body onload="setEventListener(disableKey);">
Try this if you want a numbers only textbox:
function numbercheck(event) {
var unicode = event.charCode; var unicode1 = event.keyCode; if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Safari") != -1) {
if (unicode1 != 8) {
if ((unicode >= 48 && unicode <= 57) || unicode1 == 37 || unicode1 == 39 || unicode1 == 35 || unicode1 == 36 || unicode1 == 9 || unicode1 == 46)
{ return true; }
else
{ return false; }
}
}
if (navigator.userAgent.indexOf("MSIE") != -1 || navigator.userAgent.indexOf("Opera") == -1) {
if (unicode1 != 8) {
if (unicode1 >= 48 && unicode1 <= 57)
{ return true; }
else
{ return false; }
}
}
}
And in your textbox call it on the onkeypress event:
onkeypress="return numbercheck(event)"

Categories

Resources