I don't know why my else statement didn't work.
It's my first time that actually happened and I checked using console.log().
This is my code:
setTimeout(function() {
var b = 2;
var d = 80000;
if ("div[class='resultInfo resultLose']") {
setTimeout(function() {
var a = ($("input[name='_4']").val().replace(/\s+/g, ''));
var c = a * b;
$("input[name='_4']").val(c);
$("input[value='Play!']").click();
}, 1000);
} else if ("div[class='resultInfo resultWin']") {
setTimeout(function() {
$("input[name='_4']").val(d);
$("input[value='Play!']").click();
}, 1000);
}
}, 4500);
I have tried to:
delete the setTimeout in if
delete the "if ("div[class='resultInfo resultWin']")"
This only uses first if even the elseif is true, I don't know what to do.
Your current if and else/if conditions are just testing the truthiness of a random string which will always evaluate to true. Since the first condition evaluates to true, you will always skip the else if condition (even though that will also evaluate to true in this instance).
What you actually seem to want to test is whether or not there are elements that exist that match the strings you have as selector strings. If that's the case, your simplest fix would be to change your if and else statements to look more like jQuery statements and checking the length of the result.
if ($("div[class='resultInfo resultLose']").length > 0)
and
else if ($("div[class='resultInfo resultWin']").length > 0)
You are having a non-empty string inside your if condition, which evaluates to true every time. So else block will never be reached.
Your code doesn't make sense.
You aren't entering the else if because your if will always evaluate to true.
if ("div[class='resultInfo resultLose']") will always be true, as you're not doing any comparision, you're evaluating a string. So that's the same as doing if (true).
I supose you're missing some code there, like a JQuery selection or something like that.
Related
I am trying to see if the user input is equal to a number, and if it isn't, then show a label saying, "Must be a number" and do not proceed until it is. I never learned about how to check if a string is equal to a number, so I searched it up and added it to my code, but it still doesn't work. Can someone look at it and tell me how I can fix my if-condition? Thank you in advance!
//variable that is used
var user_answer = getNumber("answer_input");
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN("user_answer") === false){ //here is where I tried to use it, but it just skips the condition
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
});
This is what I tried based on a comment and it still did not work:
onEvent("attackBttnForEquation", "click", function( ) {
if (isNaN(user_answer) === true){ //I forgot to specify that user_answer is a variable, but I even set the condition to equal to true and it did the same thing as before.
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
Okay, with the answer I got, the "mustBeNum_label" shows, BUT when the user inputs an actual number, it still shows "mustBeNum_label".
//Confirm your answer with clicking the button
onEvent("attackBttnForEquation", "click", function( ) {
if (Number(user_answer)){
setScreen("play_screen");
hideElement("fight_symbol");
checkAnswer();
checkLose();
} else {
showElement("mustBeNum_label");
setTimeout(function(){
hideElement("mustBeNum_label");
}, 1000);
}
});
Try checking like this:
if (Number(user_answer) || user_answer == 0) {
// input is a number
} else {
// input is not a number
}
You can find out more here: Number - MDN
I would consider this a poor case for Number() since it will output NaN or a number.
Consider when you encounter 0: the conditional will run your else block since 0 is falsey.
Number.isInteger(Number(user_input)) may be a better solution since it will always output a boolean, and if it gets passed NaN will output false.
Shorter syntax would be Number.isInteger(+user_input)
A group of me and two other people are working to make a Jeopardy game (themed around United States History questions) all in JavaScript. For our final Jeopardy screen, the two teams will each bet a certain amount of money. To prevent a team from typing in random letters for a bet (i.e typing in "hasdfhgasf" instead of an actual amount), we're trying to write an 'onEvent' command that checks to see if a bet is null. If that bet is null, then the code should come up with a message on the screen that tells them to check their bets again.
We tried using statements like, if "null" or if " " but neither of these statements works. We've worked with using getNumber and getText commands, along with just regular variable comparisons with or booleans. So far, we haven't had any luck with these methods.
Here's the group of code we're having issues with:
onEvent("finalJeopardyBetSubmit", "click", function() {
team1Bet = getNumber("team1BetInput");
team2Bet = getNumber("team2BetInput");
console.log(team1Bet);
console.log(team2Bet);
if (getText("team1BetInput") == "" || getText("team2BetInput") == "") {
console.log("Check bet!");
finalJeopardyError();
} else if ((getText("team1BetInput") != 0 || getText("team2BetInput") != 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") < 0 || getNumber("team2BetInput") < 0)) {
console.log("Check bet!");
finalJeopardyError();
} else if ((getNumber("team1BetInput") > team1Money || getNumber("team2BetInput") > team2Money)) {
console.log("Check bet!");
finalJeopardyError();
} else {
console.log("Done");
}
});
You can also check out the whole program on Code.org if you'd like to get a better look.
We expect that with the console.log commands, it should say "check bet" if the bets return as null. Instead, the code has ended up fine, and not displaying our error message, even if we type in nothing or just random letters.
a null variable will evaluate to false. Try:
if(variable){
// variable not null
}else{
// variable null
}
Convert the value to a Number first using Number(value) and then check for falsy values using the logical not ! operator. If they enter alphabetic characters, then calling Number('abc') results in NaN.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null; NaN; 0; empty string ("" or '' or ``); undefined.
The ! will change any of the falsy values above to true, so you can check for all of them with just the first if statement below.
onEvent("finalJeopardyBetSubmit", "click", function() {
// Convert these values to numbers first
var team1Bet = Number(getNumber("team1BetInput"));
var team2Bet = Number(getNumber("team2BetInput"));
if (!team1Bet || !team2Bet) {
// Handle invalid number error
}
else if (team1Bet < 0 || team2Bet < 0) {
// Handle invalid range error
}
else if (team1Bet > team1Money || team2Bet > team2Money) {
// Handle insufficient funds error
}
else {
// Finish game
}
})
You can read more about the logical operators here.
I want to be able to have an if statment saying that if an element is equal to Infinity, it gives out a different phrase than "Infinity"(my element is an input box) here is my if statement:
if (document.getElementById("box").value === Infinity) {
document.getElementById("box").value = "STOP PRESSING BUTTONS"
}
I'm still very new to javascript/html so I might've gotten some of the terms wrong.
Try this...
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ANY LOGIC
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ANY LOGIC
}
How the 'return' to give me true or false without an 'if' statment like in the first example?
Example'1':
function isEven(){
if(num % 2 === 0){
return true;
} else {
return false;
}
}
And it works, but then my teacher shorten it up like this (ex-'2'):
function isEven(){
return num % 2 === 0
}
You can return anything from the function. Please refer to the Example below to understand it.
function myFunction(val) {
console.log(test(val))
}
function test(val){
if(val==1) return 'testing';
if(val == 2) return true;
if(val == 3) return 1>2;
if(val == 4) return 2%3 == 0;
}
<button onclick="myFunction(1)">Test1</button>
<button onclick="myFunction(2)">Test2</button>
<button onclick="myFunction(3)">Test3</button>
<button onclick="myFunction(4)">Test4</button>
not a real answer, just trying to help, so don't upvote please!
I think the easiest way of understanding the basics of programming is to go back to daily life examples, so here is one:
You are talking to a friend, lets call him Bob. Bob owns an ice cream shop. It's summer. You want ice cream, so you ask him if you can get one. Bob tells you:
If there is Ice left, i can give you some, otherwise i can't.
function canIGetIceCream() {
if(isIceCreamLeft) {
return true;
} else {
return false;
}
}
However, Bob could also shorten his answer without changing the meaning:
Depends on the ice left
function canIGetIceCream() {
return isIceCreamLeft;
}
Booelans are just values, just like numbers or strings. In the first example if isIceCreamLeft is true, it will enter the first if branch and then return true, otherwise if it is false it will return false. Instead you could just return the value the boolean is holding like in the second example.
You don't really ask it by using an if statement. An if statement just checks if what's between the brackets ( ) is either true or false. Like how an addition 1 + 2 results in 3, something like 3 === 2 results in false. You can view it as a normal mathematical problem which has an answer. When your computer evaluates:
num % 2 === 0
It calculates num % 2 and checks if that's equal to 0. This can be either true or false. These are both boolean values, and are the same as in your first example. So what your first example is really doing is checking if the expression is either true or false and then returning that exact value, like so:
var num = 2;
if(num % 2 === 0){
return true;
}
After evaluation, this will basically result in:
if(true){
return true;
}
See how it's easier to just leave out the if statement and return the result of num % 2 === 0?
The thing you need to understand here is how operators work.
Operators operate on operands. An operator and one or more operands form an expression. Expressions are evaluated.
The return statement takes an expression and returns the value that the expression evaluates to. For example, 1 + 2 evaluates to 3.
Comparison and logical operators, like ==, <, and &&, generally evaluates to true or false. These work similarly: true && false evaluates to false, 1 == 1 evaluates to true.
Therefore, return num % 2 == 0 is completely valid because when the code is executed, num % 2 will be evaluated, then the whole expression will be evaluated to either true or false. You can think of the whole statement becoming
return true;
or
return false;
after the expression is evaluated.
You have an evaluation here of
num % 2 === 0
The code will check if the remainder of num divided by 2 (num % 2) is equal to 0. This can be true or false, hence it will return true of false.
I am trying to make a simple if-else statement, but when I run the code, it always returns true, even if I enter something in the prompt that I know should be false. I have ran it through JsFiddle, and it seems that the code snippet is perfectly valid.
var captchaTest = 5;
var captchaInput = prompt('What is five plus five?');
if ('captchaTest + captchaInput = 10') {
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
Can someone tell me what I did wrong?
Non-empty strings in JavaScript are truthy. 'captchaTest + captchaInput = 10', when evaluated as Boolean, is true.
You need to remove the quotation marks and change = to ==:
if (captchaTest + captchaInput == 10)
Apart from the answer that other provided I would also make a point that as per your captcha question, your condition should be like this
if (captchaInput == 10){
alert('You passed, you may continue'); window.location.href = 'pagepass.html';
}
else {
alert('Failed, try again.'); window.location.href = 'main.html';
}
I don't see any use of the variable captchaTest
You shouldn't be using a 'captchaTest + captchaInput = 10' as it is a String and always evaluates to true unless it is an empty one.
Also you should use comparison operator == instead of assignment operator =
So remove the quotes
if ((captchaTest + captchaInput) == 10)