Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want to do a simple check using the if statement, I'm comparing an element with an array using this function, I want to show the result based on the conditions but when a run the function it didn't execute the first if, even if it equal to one of the elements in the array it goes to the second statement.
function TalkTheTalk(msg) {
const talk = +msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
greetings.map((greeting)=> {
if(greeting === talk) {
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
}
else if (greeting !== talk) {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
else {
MessageEl.innerHTML = '<div>Would you repeat</div>';
}
});
}
function TalkTheTalk(msg) {
// const talk = +msg; This makes it a NaN
const talk = msg;
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
// greetings.map((greeting)=> { map means convert each one to something else, not suitable
const result greetings.find((greeting)=> {
return greeting === talk
});
if (result) {
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
} else {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
}
Javascript unary operator + is for Numbers, not for strings.
console.log(+'hello'); // NaN
There are some issues in your code.
First is const talk = +msg;
it makes greeting === talk will never be true.
And second is map function.
So the last loop condition will be render.
I think you should do like this.
function TalkTheTalk(msg) {
const talk = msg;
var MessageEl = document.getElementById("message");
console.log(talk);
var heargreeting = false
const greetings = ["I'm good", "I'm fine", "I'm Ok"];
greetings.map((greeting)=> {
if(greeting === talk) {
heargreeting = true;
}
else if (greeting !== talk) {
MessageEl.innerHTML = '<div>Sorry I didnt hear !Would you Repeat</div>';
}
else {
MessageEl.innerHTML = '<div>Would you repeat</div>';
}
});
if(heargreeting)
{
MessageEl.innerHTML = '<div> Im so happy to hear that! what can i do for you today ! </div>';
}
}
TalkTheTalk("I'm good");
<div id="message"></div>
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I'm doing a project on codecademy, and one of the bits of code I have to write looks like this:
const calculateSleepDebt = () => {
const actualSleepHours = getActualSleepHours();
const idealSleepHours = getIdealSleepHours();
if (actualSleepHours === idealSleepHours) {
console.log('You got the perfect amount of sleep!');
} else if (actualSleepHours > idealSleepHours) {
console.log('You got too much sleep!');
} else (actualSleepHours < idealSleepHours) {
console.log('You did not get enough sleep!');
}
};
I get an "unexpected token" error message.
The code is supposed to take the values of the getActualSleepHours and getIdealSleepHours functions/variables, compare them, and log the correct statement.
While trouble shooting, I found that deleting the curly brackets around the else statement removes the error message, and logs the else if statement, the else statement, and an 'undefined'. I don't know if that is relevant as I'm new to this.
I tried turning it into a switch statement, like:
switch {
case (actualSleepHours === idealSleepHours) :
console.log('yadda yadda');
break;
but no luck either.
Thanks for reading!
Your "else" have an arguments, but this is not right
const calculateSleepDebt = () => {
const actualSleepHours = getActualSleepHours()
const idealSleepHours = getIdealSleepHours()
if (actualSleepHours === idealSleepHours) {
console.log('You got the perfect amount of sleep!')
}
else if (actualSleepHours > idealSleepHours) {
console.log('You got too much sleep!')
}
else{
console.log('You did not get enough sleep!')
}
};
Try this! Sorry for my english <3
Background
I'm working on a survey in javascript which contains ten "yes" or "no" questions. I'd like to code the "yes" responses to = 1 and the "no" responses to = 0. I'm using the html tag so they can only choose one or the other.
Then I'd like to have the sum of their responses added up and divided by the total number of questions to yield a percentage. Depending on their percentage, I would then like to output some HTML text to a field below it with some helpful tips and advice relevant to their score.
To be clear, though I'm learning javascript now, I don't expect anyone to code the thing for me, but I'd just like to know where I should be looking for answers to make this happen. I'm thinking I need to use the if/else conditions to account for the yes/no responses and then maybe I need another function() to do the rest of the calculations.
I've tried a number of different variations of if/else statements but I'm just confused about how to 1) code the yes/no responses; 2) integrate them into if/else statements.
I'll add an abbreviated snippet of code with two sample questions that I'm trying to get working now.
function calc (form) {
var score1;
var score2;
var Result = form.Result.value;
if (form.Question1.options[form.Question1.selectedIndex].value = "Yes") { score1 = 1;
} else {
score1 = 0;
}
if (form.Question2.options[form.Question2.selectedIndex].value = "Yes") { score2 = 1;
} else {
score2 = 0;
}
Result = (((score1 + score2) / 10) * 100);
if (Result == 80) {
document.getElementById("recommendation").innerHTML = "<h4>Heading here</h4> <p>Advice goes here based on their result</p>"
}
}
To be fair, I believe you need to rethink your approach. Having an if-then-else approach for each question & answer can be quite tedious in maintaining or when you want to change the answers.
If you would create a data structure for your questions, you could use for-loops or saving indexes of the current question to handle an answer. The correct answer would then also be part of your data structure (but that is up to you, it could be a client/server request as well).
You already got some answers why your current approach doesn't work due to missing up assignment with equality operators, but I thought I would give you an alternative solution.
This solution will create a dynamic ui, and handle answers on questions when the next button is clicked. The questionaire here is unidirectional, you can only go forward :)
It is mainly to give you an idea how to approach it differently. I don't imagine you actually using this code as is.
The code has quite some inline comments, and is based on the usage of a generator function (which are not supported by Internet Explorer, but should be fine in any other browser)
Upon completion, the score would be displayed in a message box.
// data structure that takes question / answer / which is correct and the points attributed
const questions = [
{
question: 'What platform are you on?',
answers: ['Stackoverflow', 'codereview'],
correct: 0,
points: 5
},
{
question: 'What is the answer to everything',
answers: [42, 'I don\'t have a clue'],
correct: 0,
points: 1
},
{
question: 'How much is 7*6',
answers: ['I am not good with maths', 42],
correct: 1,
points: 10
}
];
// a simple generator that is used in the questionaire
function *questionsGenerator( questions ) {
yield* questions;
}
// creates a questionaire, with forward only options (due to the use of the generator function)
// all variables are locally scoped, when all questions were answered, the onCompleted callback would be called
// it returns an object with nextQuestion function though it could call nextButton internally, and you just have to call the function once if you would want to change it
const questionaire = ( query, nextButton, target, onCompleted ) => {
let score = 0;
let iterator = questionsGenerator( query );
let question = null;
let selectedAnswer = -1;
nextButton.addEventListener('click', nextQuestion);
function evaluateAnswer() {
if (!question) {
// no question yet
return;
}
if (selectedAnswer < 0) {
return;
}
if (question.correct === selectedAnswer) {
score += question.points;
}
return;
}
function nextQuestion() {
evaluateAnswer();
question = iterator.next();
// this is a bit of a hack to check if we just had the last question or not
if (question.done) {
nextButton.removeEventListener('click', nextQuestion);
onCompleted( score );
return;
}
question = question.value;
drawUI();
}
function drawUI() {
// disable next button
nextButton.setAttribute('disabled', true);
selectedAnswer = -1;
// remove existing items
Array.from( target.childNodes ).forEach( child => target.removeChild( child ) );
// create new questions (if available)
const title = document.createElement('h1');
title.innerHTML = question.question;
target.appendChild( title );
question.answers.map( (answer, i) => {
const el = document.createElement('input');
el.type = 'radio';
el.name = 'answer';
el.value = i;
el.id = 'answer' + i;
el.addEventListener('change', () => {
selectedAnswer = i;
nextButton.removeAttribute('disabled');
} );
const label = document.createElement('label');
label.setAttribute('for', el.id );
label.innerHTML = answer;
const container = document.createElement('div');
container.appendChild(el);
container.appendChild(label);
return container;
} ).forEach( a => target.appendChild( a ) );
}
return {
nextQuestion
}
};
// create a questionaire and start the first question
questionaire(
questions,
document.querySelector('#btnNext'),
document.querySelector('#questionaire'),
score => alert('You scored ' + score )
).nextQuestion();
<div id="questionaire">
</div>
<div class="toolstrip">
<button id="btnNext" type="button">Next</button>
</div>
If you want to check for equality use == or ===. == will check if the values are the same,
=== will also check if the types are the same.
For example:
0 == "0" => true
0 === "0" => false.
Thank you for answering my original question, and the reason i am simply editing this post for my second question about this code is because the site wont let me make very many questions. my question is why isnt makesjump1 randomly true or false? it always seems to come out true. please help #Yhlas and #codeConcussion
var isjumping1 = true;
while(isjumping1) {
var makesjump1 = Math.random()
if(makesjump1 => .51) {
makesjump1 = true }
else if(makesjump1 <= .50) {
makesjump1 = false }
var jump1 = prompt("Do you choose to JUMP, or let the fairies help you FLY").toUpperCase()
switch(jump1) {
case 'JUMP':
if(makesjump1 = true) {
console.log("You made the jump on your own, so the fairies reward you with a steel sword(9 DMG)")
damage = 9;
weapon = 'steel sword(9 DMG)'; }
else if(makesjump1 = false) {
console.log("You attempt the jump but miss it, and are hanging on by a thread")
console.log("The fairies rescue you, but you got scratched up, doing 3 damge to you.")
health = health - 3; }
isjumping1 = false;
break;
case 'FLY':
console.log("The fairies help you over the pit")
isjumping1 = false;
break;
default:
alert("That was not a choice!")
break; }
}
You're assigning it to true with every loop. Use == instead or just...
while(isjumping1)
while(isjumping1==1) - comparison
while(isjumping1=1) - assignment(always returns true)
The way that you're assigning the random value to makesjump1 is incorrect. It would fail if Math.random() returned a value in the range (0.50,0.51). Instead, try this:
var makesjump1 = Math.random()<0.5;
I am trying to create a JavaScript Quiz.
The function will check the user's input value.
If it is correct; it will change the question.
Exact Code See JSFiddle
There are probably many more efficient and conventional ways to achieve what I am trying to do. Current issue is the function runs from the top every time it runs(obviously)
function checkAnswer() {
var question = document.getElementById("ques").innerHTML;
var userAnswer = document.getElementById("answer").value;
if (userAnswer === "New York City") {
alert("correct!");
question = "What is the best college football team?";
if (userAnswer === "Alabama") {
alert("Correct!");
question = "Next question will go here and so on..."
}
}
}
In no way would I suggest doing things this way, but here's how to get your jsfiddle to work:
function check() {
var question = document.getElementById('question').innerHTML
var userAnswer = document.getElementById("answer").value;
//Makes answer lowercase
userAnswer = userAnswer.toLowerCase();
//question one
if (question === "Write One, Two, Three..") {
if (userAnswer === "one two three") {
alert('correct');
}
else {
alert('Sorry Wrong!');
}
//question two
document.getElementById('question').innerHTML = "Write 4, 5, 6";
}
else {
if (userAnswer === "4 5 6") {
alert("correct!");
}
else {
alert('Sorry Wrong!');
}
}
}
One simple way to do what you want is to put your questions in an array:
var QandA = [
["question1...", "answer1...."],
["question2...", "answer2...."],
["question3...", "answer3...."],
["question4...", "answer4...."]
];
function check()
{
// No more questions?
if (0 === QandA.length) return;
// Check answer
var userAnswer = document.getElementById("answer").value.toLowerCase();
if (userAnswer === QandA[0][1]) {
alert("Correct");
}
else {
alert("Incorrect");
}
// Delete that question
QandA.shift();
// And move to next
if (0 != QandA.length) {
document.getElementById('question').innerHTML = QandA[0][0];
}
}
If you have a number of questions that you need validating I would take the following approach. It allows you as many questions as you like without repeating code.
First, store your questions in an array:
var arr = ["one two three", "4 5 6"];
Set a counter to zero, and a total (to measure the user performance):
var count = 0;
var total = 0;
Cache the elements:
var questionEl = document.getElementById('question');
var userAnswerEl = document.getElementById("answer");
Separate out the code that writes the question into a new function. It writes the question based on the counter:
function writeQuestion() {
if (count < arr.length) {
questionEl.innerHTML = "Write " + arr[count];
} else {
alert('No more questions. You have scored ' + total);
}
}
function check() {
userAnswer = userAnswerEl.value.toLowerCase();
if (userAnswer === arr[count]) {
alert('correct');
count++;
total++;
writeQuestion();
} else {
alert('Sorry Wrong!');
count++;
writeQuestion();
}
}
DEMO
if (userAnswer === "New York City") {
alert("correct!");
question = "What is the best college football team?";
if (userAnswer === "Alabama") {
alert("Correct!");
question = "Next question will go here and so on..."
}
}
This block only runs if userAnswer is "New York City", but inside it, you test whether userAnswer is "Alabama" - that will never be true. You probably want to move the second if outside of the first if block.
You seem to be assigning to question but not using the value. If you think you are updating the question text by assigning a value to question that isn't going to work. I think you are trying to do this:
question = document.getElementById("ques");
// later on...
question.innerHTML = "this is another question";
// even later...
question.innerHTML = "and here is a new question";
That would update the page for you because question would point to a DOM node and you can set .innerHTML on that, but the way you wrote it, you're setting question to a string value initially, and then other string values later, but not using any of them in anyway.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Am learning Javascript in code academy. This is the test I have been given,
"Inside the eat function, create an if statement that returns true only if both hungry and foodHere are true, and false otherwise."
My code below is executing but it has a warning. What could be the problem?
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere = false){
console.log("Choose one");
}
};
eat();
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else {
console.log("Choose one");
}
};
eat();
the problem was, that you tried to assign a value in the condition foodHere = false. If you want to compare things you need == and if you want to be sure that the types are the same use ===.
But you don't need that condition at all!
The assignment want you to return a boolean value (true or false) and not to print something, so i guess your code should look like this:
var hungry = true;
var foodHere = true;
var eat = function() {
return (hungry && foodHere)
};
eat();
Single = is for assignment, == is for comparison
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(hungry && foodHere == false){
console.log("Choose one");
}
};
eat();
Anyways, you don't need the second comparison since if the first one is false it will always go through the else
I just want to give additional information for emilioicai's answer, there are two kind of "equal comparison" in JavaScript
equal to ( == )
exactly equal to ( === )
Reference: http://www.w3schools.com/js/js_comparisons.asp
= is for assignment, == is for value comparison and === is for value and datatype comparison. So you can use == while comparing with the false. But this is not the best practice. We always uses '!' negation operator while converting true to false
var hungry = true;
var foodHere = true;
var eat = function() {
if(hungry && foodHere){
console.log("I am hungry");
}else if(!hungry || !foodHere){
console.log("Choose one");
}
};
eat()
I am using || operator assuming that any one needs to be false.You can go for && if both false are required