This question already has answers here:
Javascript - turning if statement into switch statement
(1 answer)
JavaScript switch with logical operators?
(5 answers)
Closed last month.
This feels like a silly question but I can't get it to work:
I am building an event handler that I want to trigger two different outcomes if the user presses "enter" or "shift Enter"
I have this code
switch(e){
case (e.keyCode == 13 && !e.shiftKey):
console.log("Enter")
break;
case (e.keyCode == 13 && e.shiftKey):
console.log("Enter&Shift")
break;
default:
console.log(`Sorry, we are out of it.`);
}
but something is not working because it always go to default...despite the fact that e.keyValue is actually 13 and e.shiftKey is true...so I am passing the event correctly.
It's the switch that is wrongly built.
You shouldn't use a switch statement for this, but regular if and else statements.
if (e.keyCode == 13 && !e.shiftKey) {
console.log("Enter");
} else if (e.keyCode == 13 && e.shiftKey) {
console.log("Enter&Shift");
} else {
console.log(`Sorry, we are out of it.`);
}
Related
This question already has answers here:
How do I test if a variable does not equal either of two values?
(8 answers)
Closed 10 months ago.
Just got started with Javascript and struggling with some pretty easy code:
"use strict";
function math () {
if (action == "+") {
return answer = firstNumber + secondNumber
}
else if (action == "-") {
return answer = firstNumber - secondNumber
}
else {
while(action != "+" || action != "-") {
action = prompt('Write an action (only "+" and "-" supported!!!):');
}
}
}
math(firstNumber, secondNumber,action);
alert(answer);
Even after condition in loop is false the loop still executes. Can you please explain what went wrong? Not just solution, please.
while(action != "+" || action != "-") will always evaluate to True
while(action != "+" && action != "-") is what you are looking for
The error here lies in the while loop conditional statement.
while(action != "+" || action != "-")
This statement will continue looping if action does not equal "+", or "-". If action is "+", we continue to loop because the action does not also equal "-". To fix this change your operator to an && instead of an || like this:
while(action != "+" && action != "-")
I guess, you just made an error when formulating your condition and most likely only want to continue looping until the entered action is neither of the two values. You therefore must use the and && and not the or || operator.
In other words: you want to continue until the value is not a plus sign AND not a minus sign.
First of all you don't need to write a while block there as when the compiler will check first two if statements that is if and else if (in order) and will not execute any of them this automatically means that action != "+" and also != "-" so you can directly write like this :
"use strict";
function math () {
if (action == "+") {
return answer = firstNumber + secondNumber
}
else if (action == "-") {
return answer = firstNumber - secondNumber
}
else {
action = prompt('Write an action (only "+" and "-" supported!!!):');
}
}
}
math(firstNumber, secondNumber,action);
alert(answer);
Also it is not stopping because it will run until the while condition is False but if the action is != "+" or "-" this means while condition will always be true because wrong action has been taken, so while loop will run infinitely... Try replacing while with "if statement" or the || operator in while loop with && operator
This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 2 years ago.
I need a breakdown in laymans terms as to where I am going wrong with getting my else statement to work. I thought I had figured it out but don't understand something as I keep running into this issue. Thanks
if (country === "Brazil" || "Portugal") {
alert("You speak Portuguese");
} else {
alert("You don't speak Portuguese");
}
You need to do the following:
if (country === "Brazil" || country === "Portugal") {
alert("You speak Portuguese");
} else {
alert("You don't speak Portuguese");
}
Let me know if it helps.
I'm trying to get a response for when visitor uses the keys right and left
<script>
$(document).keypress(function(event) {
key = String.fromCharCode(event.which)
if(key == '37' || key == '39') {
$('main').html('You pressed : ' + key)
event.preventDefault()
}
});
</script>
It's not working. what did work was the line
if(key == 'a')
I used this table to find the code https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Is it because jQuery has different table? or maybe I should load JavaScript as well? then how do I do use the two of them? (jQuery and JavaScript?)?
EDIT:
I think I got it
String.fromCharCode(event.which)
JavaScript can't read strings as numbers? do I need to use different function? I'm new to this can you tell me what to do?
I find for myself that when I go to implement these sorts of "get item from event", that a simple console.log(event) does wonders. I'd start with:
$('body').on('keypress', function(evt){
console.log('Event: ', evt);
});
Then, press the right and left arrow keys and see what happens.
First, an observation: I note that you're comparing the string '37', which is distinct from the integer value 37. The former is two or four bytes (depending on how the JS implementation stores characters), while the latter is one byte. Is that your intention after reading the appropriate APIs?
Second, as a specific suggestion, if you're using jQuery, take advantage of it's normalization routines. In this case, event.which is returning 0, but you can use event.keyCode which is probably what you want to compare:
if ( 37 === event.keyCode ) {
// ...
}
else if ( 39 === event.keyCode ) {
// ....
}
What you want to use is the keydown event. Also, no reason to use the String.fromCharCode, you can just compare the integers. Something like this would work
$(document).keydown(function(event) {
if (event.which == 37 || event.which == 39) {
var key = event.which == 37 ? 'left' : 'right';
$('main').html('You pressed : ' + key)
event.preventDefault()
}
})
In Javascript, I have callback function for keydown event. I use keyCode and which properties to detect which keys user pressed.
var keyPressed = event.keyCode || event.which;
if (keyPressed > 47 && keyPressed < 58) {
//do something
}
It works well. However, this properties are deprecated, I switch to key property. When I replace code, it does not work correctly.
if (event.key > 47 && event.key < 58) {
//do something
}
I can't check user's pressed key in range.
For printable characters, .key() returns a non-empty Unicode character string containing the printable representation of the key.
Essentially: for ASCII characters, you get the character itself rather than its ASCII code.
So, for digits you could just do:
var myInput = document.getElementsByTagName('input')[0];
myInput.addEventListener("keydown", function(event) {
if(event.key >= "0" && event.key <= "9") {
console.log('digit: ' + event.key);
}
});
<input>
For letters, you'll also have to check that .key() returns a single character because a non-printable key such as delete will be encoded as "Delete", which would pass the test "Delete" >= "A" && "Delete" <= "Z".
var myInput = document.getElementsByTagName('input')[0];
myInput.addEventListener("keydown", function(event) {
if(event.key.length == 1 && event.key >= "A" && event.key <= "Z") {
console.log('capital letter: ' + event.key);
}
});
<input>
According to
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
"The KeyboardEvent.key read-only property returns the value of a key or keys pressed by the user."
The values that get returned are strings. You would probably have to remain using key.code if you want to check range.
Alternatively you could use switch statements like in the example on mdn
switch (event.key) {
case "ArrowDown":
// Do something for "down arrow" key press.
break;
case "ArrowUp":
// Do something for "up arrow" key press.
break;
case "ArrowLeft":
// Do something for "left arrow" key press.
break;
case "ArrowRight":
// Do something for "right arrow" key press.
break;
case "Enter":
// Do something for "enter" or "return" key press.
break;
case "Escape":
// Do something for "esc" key press.
break;
default:
return; // Quit when this doesn't handle the key event.
}
Or event still make an array like
var validKeys = ["ArrowDown", "ArrowUp", ...]
and then check to see if the event.key is in the array.
Finally you could use regular expressions
This should work
<script type="text/javascript">
document.addEventListener('keydown', function(event){
var charTyped = event.key;
if (/^[a-z\d]$/i.test(charTyped)) {
console.log("Letter or number typed: " + charTyped);
}
})
</script>
Greetings all. I have the following function to validate input depending if is numeric, alpha, alphanumeric and email:
function permite(e, permitidos) {
var key = e.keyCode || e.which;
//Validate if its an arrow or delete button
if((key == 46) || (key == 8) || (key >= 37 && key <= 40))
return true;
var keychar = String.fromCharCode(key);
switch(permitidos) {
case 'num':
permitidos = /^[0-9]$/;
break;
case 'car':
permitidos = /^[\sa-zA-Z]$/;
break;
case 'num_car':
permitidos = /^[\sa-zA-Z0-9]$/;
break;
case 'correo':
permitidos = /^[a-zA-Z0-9._\-+#]$/;
break;
}
return permitidos.test(keychar);
}
The var names are in spanish but its an easy function to understand.
The problem is the following. The keycode for '%' is 37 the same than the left arrow and the keycode for '(' is 40 the same than the right arrow. So my function is not validating '%' and '(' and it sucks. I dont know what to do, please help.
The keypress event doesn't fire for arrow and delete keys, so you can just remove your if statement. Darn you FireFox!
You are mixing up keyCode and charCode, which is understandable because event.keyCode actually contains charCode for keyPress events, unlike keydown and keyup. The keyCode for ( is 57 (same as for 9 - those characters are on the same key). Its charCode is 40. Arrow keys don't have charCodes, so they don't fire keypress events. (Except in FireFox... Argh!)
Your best bet is to use the keydown event and look for keyCode rather than charCode, checking for shift keys when necessary. You'll have to manually map keyCodes to characters when the shift key is pressed.
Slightly OT (apologies) but you may want to look at one of the Javascript libraries out there, for example JQuery; almost all of them come with (or have) libraries for "validating input".
For example: if you were using JQuery you may consider the "Validation" plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Check for whether the shift key is being pressed as well by checking event.shiftKey:
//Validate if its an arrow or delete button
if((key == 46) || (key == 8) || (key >= 37 && key <= 40 && !e.shiftKey))
return true;
Another option (depending on your application) is to handle the keydown event instead of the keypress event, which won't result in overlapping key codes.