I'm new to this site and currently doing a computer programming class up in ontario, canada. I have a computer programming class and currently making an interactive tic-tac-toe game. I use if statements in a function in order to verify in theres a winner. I have an If and an else if. However only the first if works and does its code. When i try to do the conditions for do into the else if it doesn't works. However, if i swap my else if and if so that both conditions are swapped. again only first first works and second will never work. so to me it sounds like my conditions are good. i dont know if this makes sense lol
function verifie_gagnant()
{
if (document.getElementById("centregauche").firstChild.classList.contains("markX") &&
document.getElementById("centrecentre").firstChild.classList.contains("markX") &&
document.getElementById("centredroite").firstChild.classList.contains("markX") ||
document.getElementById("centregauche").firstChild.classList.contains("markO") &&
document.getElementById("centrecentre").firstChild.classList.contains("markO") &&
document.getElementById("centredroite").firstChild.classList.contains("markO"))
{
document.getElementById("winner").innerHTML= tours + " a ete vaincu!!";
}
else if (document.getElementById("hautgauche").firstChild.classList.contains("markX") &&
document.getElementById("hautcentre").firstChild.classList.contains("markX") &&
document.getElementById("hautdroite").firstChild.classList.contains("markX") ||
document.getElementById("hautgauche").firstChild.classList.contains("markO") &&
document.getElementById("hautcentre").firstChild.classList.contains("markO") &&
document.getElementById("hautdroite").firstChild.classList.contains("markO"))
{
document.getElementById("winner").innerHTML= tours + " a ete vaincu!!";
}
}
By hearing to your problem it looks like in all the cases both the condition are true. Hence which ever condition is first it executes that first skipping the else part. You can test this removing the else and keeping both in separate if condition. You will notice it navigate inside both if condition. You need to change you IF condition. See below to know more on If condition
IF is a Conditional Statements. ... Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
You have an || between && conditions which is evaluating to true in both if and else if.
So even if you swap conditions it always execute first one.
Try putting ( condition1 && condition2) || (condition3 && condition4) in both if and elseif conditions
Example fix. (You need to see where actually you need to group conditions)
function verifie_gagnant()
{
if ((document.getElementById("centregauche").firstChild.classList.contains("markX") &&
document.getElementById("centrecentre").firstChild.classList.contains("markX") &&
document.getElementById("centredroite").firstChild.classList.contains("markX")) ||
(document.getElementById("centregauche").firstChild.classList.contains("markO") &&
document.getElementById("centrecentre").firstChild.classList.contains("markO") &&
document.getElementById("centredroite").firstChild.classList.contains("markO")))
{
document.getElementById("winner").innerHTML= tours + " a ete vaincu!!";
}
else if ((document.getElementById("hautgauche").firstChild.classList.contains("markX") &&
document.getElementById("hautcentre").firstChild.classList.contains("markX") &&
document.getElementById("hautdroite").firstChild.classList.contains("markX")) ||
document.getElementById("hautgauche").firstChild.classList.contains("markO") &&
document.getElementById("hautcentre").firstChild.classList.contains("markO") &&
document.getElementById("hautdroite").firstChild.classList.contains("markO")))
{
document.getElementById("winner").innerHTML= tours + " a ete vaincu!!";
}
}
This is the first thing you can fix (syntax) after this you need to actually see what is the actual data returned after the single condition is evaluated. Maybe both have same data.
Related
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.
Just trying to understand on why Buzz doesn't appear in the newline after Fizz for 15.
Trying to learn JavaScript from Eloquent Javascript and just got into doing the FizzBuzz exercise. Note that I've included a commented out solution where it does work (although not elegantly) but the thing I've notice that some solutions searched online show their 15 appearing with Fizz but Buzz is on a newline while my solution (which is not commented out) only shows Fizz.
Can anyone explain to me why does it do this? Just curious. The only thing I've noticed is when I use
if ((int%3 == 0) && (int%5 == 0))
either at the end or the beginning of the block is when the changes are visible.
Note:
I'm not asking for solutions. I just want an explanation to my question above. The commented solution does give me FizzBuzz for 15. Please do not misunderstand and thank you for taking your time to answer this.
My solution:
for(let int = 1; int <= 100; int++){
if(int%3 == 0){
console.log('Fizz');
}
else if(int%5 == 0){
console.log('Buzz');
}
else if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
}
/*if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
}
else if(int%3 == 0){
console.log('Fizz');
}
else if(int%5 == 0){
console.log('Buzz');
}*/
else{
console.log(int);
}
}
In you solution, the following block is dead code :
else if ((int%3 == 0) && (int%5 == 0)){
console.log('Fizz'+'Buzz');
This console.log('Fizz'+'Buzz') can never be reached because ((int%3 == 0) && (int%5 == 0)) would mean that (int%3 == 0) and so the first if is executed. Because of the meaning of else if, this later code block is never reached.
So to answer directly :
show their 15 appearing with Fizz but Buzz is on a newline
This probably is a coding error as FizzBuzz usually requires writing "Fizz Buzz" on a single line for 15. I would guess they did not use any "else if" - which you did.
my solution (which is not commented out) only shows Fizz.
Can anyone explain to me why does it do this.
Because else if blocks order is important, and you chose the wrong one.
If you remove else from else if(int%5 == 0) you will get your desired output I guess.
You should reverse the order of your if statements as you have in the commented out section. Otherwise, when int = 15, your code will match true for
if(int%3 == 0){
console.log('Fizz');
}
And it will never reach the other if statements.
When I make a conditional on jQuery that specifies to make something if an input OR a select list is empty, jQuery works fine:
if((($('input[name=su_name]').val())=="") || ($('select[name=su_family]').val())=="0")
{...}
But when I try to make it check 3 fields (if one, or the other, or the other is empty), I have a syntax error focusing the second "||". Is it not possible to set two "||" (OR) on the same conditional? This does not work:
if((($('input[name=su_name]').val())=="") || ($('select[name=su_family]').val())=="0") || ($('input[name=su_abbrev]').val())=="")
{...}
I don't know why you're using so many parenthesis in that second example, but this should work:
if ( $('input[name=su_name]').val() == "" || $('select[name=su_family]').val() == "0" || $('input[name=su_abbrev]').val() == "" )
You've used so many redundant (), instead you can just do:
if ($('input[name=su_name]').val() == "" || $('select[name=su_family]').val() == "0" || $('input[name=su_abbrev]').val() == "") {
// Your code here
}
I'm trying to adapt a calculator that was made by someone else who used to work at my company. Unfortunately I can't get hold of him at all and was wondering if someone here could help me. My javascript knowledge is limited so please bear with me if this sounds a stupid question or if I'm missing something obvious. I can't find any info on this elsewhere, so any help would be much appreciated!
Here is the current code for the section I want to change:
function date(){
var the_date = new Date();
enter code herevar the_year = the_date.getFullYear();
ret_age=Number(document.calculator.year.value);
gender=Number(document.calculator.sex.value);
a=the_year-ret_age;
if (a<=36)
{
document.calculator.number3.value=68;
}
else if (a>36 && a<=45)
{
document.calculator.number3.value=67;
}
else if (a>=45 && a<=60)
{
document.calculator.number3.value=66;
}
else if (a>60 && gender==1)
{
document.calculator.number3.value=65;
}
else if (a>60 && gender==0)
{
document.calculator.number3.value=65;
}
else
{
alert("Our calculator is having trouble working out your state
pension age. You have been given a default age of 68. Feel free to
change it.");
document.calculator.number3.value=68;
}
}
I want to add in these new 'else if' options, but I think that there is a problem with the number of conditions in each.
else if (a>60 && gender==0)
{
document.calculator.number3.value=65;
}
else if (a>60 && <=62 && gender==0)
{
document.calculator.number3.value=62;
}
else if (a>63 && gender==0)
{
document.calculator.number3.value=60;
}
Am I doing something wrong with trying to use eg. a<61 && <=63 alongside the gender condition? This appears to only work when I say one condition for the number, eg. a<60
Is there any way to use these two conditions in the else if, or will I have to do something different?
It would be great if someone could help - again, apologies if this question is poorly explained. If you need any more info to help then please let me know! I'm not sure what I'm doing. Thank you! :)
You missed an 'a' after '&&' on this condition: else if (a>60 && <=62 && gender==0)
The && indicates that another condition most be true in order for the if statement to validate to true. It does not apply a condition statement to the previous variable.
For example if you had two if statements as follows:
if(x > 1){
if(y < 1){
// do something
};
};
They could be combined into a singly if statement like this:
if(x > 1 && y < 1){
// do something
};
Essentially both sides of the && (or || for an "or" condition) need to be able to evaluate outside of the other statements.
So in your case as previously stated in another answer, you need to changes your if statement from:
else if (a>60 && <=62 && gender==0)
{
document.calculator.number3.value=62;
}
To:
else if (a>60 && a<=62 && gender==0)
{
document.calculator.number3.value=62;
}
your coditions inside the if statements are wrong
replace else if (a>60 && <=62 && gender==0) with else if (a>60 && a<=62 && gender==0)
Code:
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value!GenderField.value) {
alert('No criteria Added');
return;
}
The alert is not called when all the text fields are blank.
You're missing the && between the last two criteria
It should be:
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value && !GenderField.value)
In cases like this, it makes a lot of sense to format your if statement like this:
if ( !IDTextField.value
&& !FirstNameField.value
&& !LastNameField.value
&& !DateOfBirthField.value
&& !GenderField.value)
If you do it this way, you can't make the mistake you just made.
xbonez got it right. You are missing && between last two expression.
For something not so important, I would like to get all expressions evaluated using || and then add negation using !, rather than negating all expression and evaluate them with &&. This can make this expression a little faster, if am not wrong.
if (!(IDTextField.value || FirstNameField.value ||
LastNameField.value || DateOfBirthField.value || GenderField.value)) {
alert('No criteria Added');
return;
}
Tell me what you all think??
What is this little abomination?
... !DateOfBirthField.value!GenderField.value
I think that should be:
... !DateOfBirthField.value && !GenderField.value
You should write your code like this
if (!IDTextField.value && !FirstNameField.value &&
!LastNameField.value && !DateOfBirthField.value && !GenderField.value) {
alert('No criteria Added');
return;
}
You're missing the && between the last two criteria
the && is missed ,add it and try ,should work if no other errors exist