Javascript: How to execute through entire code and loop again - javascript

How do I make the code reprompt in a loop? I want to make the code prompt, and then with the prompted number, execute the following code. However, it continues to just keep prompting, even when I input a number.
In short, I want it to execute num1 prompt, then execute the for loop and display the content on the web browser as well as looping to reprompt for num1 at the same time.
var num = 10;
do {
var num1 = prompt("Enter a number");
for (num2 = 0; num2 < 11; num2++) {
var sum = Number(num1) * Number(num2);
document.write("<p>" + num1 + " X " + num2 + " = " + sum + "</p>");
}
}
while (num == 10);

Edit: If you are looking to add a delay between each iteration, here's how I would do that:
(function display (p) {
var num1 = +prompt("Enter a number")
for (var num2 = 0; num2 < 11; num2++) {
p.textContent = num1 + " X " + num2 + " = " + (num1 * num2)
document.body.appendChild(p.cloneNode(true))
}
(num1 == 10) || setTimeout(display, 500, p)
})(document.createElement('p'))
Your problem is that num never changes. You should be checking whether num1 matches a specific number (like 10) in your do-while loop and then exit based on that condition:
do {
var num1 = prompt("Enter a number");
for (num2 = 0; num2 < 11; num2++) {
var sum = Number(num1) * Number(num2);
document.write("<p>" + num1 + " X " + num2 + " = " + sum + "</p>");
}
}
while (num1 != 10);

First of all your end condition is on a variable you don't use at all, and it should be in the opposite sense, since the condition determines when to continue the loop, not when to exit (hence, while).
Secondly, Chrome processes Javascript first before updating the browser page, and as prompt completely blocks Javascript, you don't see the page being updated with what just has been written with document.write. Only when the loop can exit will you see the actual change on the page. This is how it works in Chrome. Other browsers do display the results on the page in combination with prompt (e.g. Firefox).
Here is a work-around based on a timer:
var timer = setInterval(function () {
var num1 = prompt("Enter a number");
for (num2 = 0; num2 < 11; num2++) {
var sum = Number(num1) * Number(num2);
// Add HTML. Don't use document.write as it will clear the page.
document.body.insertAdjacentHTML('beforeend',
"<p>" + num1 + " X " + num2 + " = " + sum + "</p>");
}
if (num1 == 10) clearInterval(timer); // stop repeating
}, 100); // Allow 100ms time for Chrome to update page
As your code now runs asynchronous, you should step away from using document.write, which would clear your page if run asynchronously. It is better to always avoid the use of document.write because of this.

Related

How to detect math operator on current html page so that my code can assign the correct sum

I have been working on a maths project for my son, and am currently struggling to attach the correct maths sum to the correct math operator currently shown on the website.
The function mathOperator() aims to identify what math operator is currently on page and then supply the correct sum.
Then i am trying to check if the textContent of the chosen clicked answer matches that sum or not using the anonymous function below mathOpertor().
I am getting no errors in the console but the code is annoyingly just adding num1 and num2 together no mater which math operator is currently active.
I figure the problem is within the lines:
let operator = num1 + num2;
if (this.textContent == operator) { }
I figured (let operator) would be mutated to the condition that was met within the mathOperator() function, but this is not the case!
Here is my code below:
//Globals
const arrLength = 10
const randomArr = []
//push random numbers to randomArr.
for (let i=0; i<arrLength; i++) {
randomArr.push(Math.floor(Math.random() * 10));
}
//DOM targets
//first and second numbers.
const num1 = document.getElementById("num1").textContent = randomArr[0];
const num2 = document.getElementById("num2").textContent = randomArr[1];
//Multiple choice answers
let option1 = document.getElementById("option1").textContent = randomArr[2];
let option2 = document.getElementById("option2").textContent = randomArr[3];
let option3 = document.getElementById("option3").textContent = randomArr[4];
//Places the correct asnwer randomly within the 3 multiple choice answers.
const correctAnswerPosition = Math.floor(Math.random() * 3);
document.querySelectorAll(".options h1")[correctAnswerPosition].textContent = num1 + num2;
//function to decide how to calculate equation depending on what HTMLpage you are on.
function mathoperators(sum) {
if (document.querySelector(".wrapper div").children[1].textContent == "+") {
sum = num1 + num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "-") {
sum = num1 - num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "*") {
sum = num1 * num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "/") {
sum = num1 / num2;
}
}
//What do to if you pick right or wrong answer.
for (let a=0; a<document.querySelectorAll(".options").length; a++) {
//targets the 3 divs that contain random incorrect answers plus correct answer.
document.querySelectorAll(".options")[a].addEventListener("click", function() {
let operator = num1 + num2;
if (this.textContent == operator) { //problem here i don't know how to connect this to sum in math operators function.
const correct = new Audio("Sounds/correct.mp3");
correct.play();
document.querySelector(".wrapper").style.display="none";
document.querySelector(".well-done").style.display="block";
setTimeout(function() {
location.reload();
}, 3000);
} else {
const incorrect = new Audio("Sounds/incorrect.mp3");
incorrect.play();
}
mathoperators(operator)
})
}
function reload() {
reload = location.reload();
}
Thankyou for your time in advance.
# bergi, Thanks very much this is the push in the right direction I needed, the changes have been made below:
function mathoperators() {
if (document.querySelector(".wrapper div").children[1].textContent == "+") {
return num1 + num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "-") {
return num1 - num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "*") {
return num1 * num2;
} else if (document.querySelector(".wrapper div").children[1].textContent == "/") {
return num1 / num2;
}
}
//What do to if you pick right or wrong answer.
for (let a=0; a<document.querySelectorAll(".options").length; a++) {
document.querySelectorAll(".options")[a].addEventListener("click", function() {
const number = parseFloat(this.textContent)
if (mathoperators() === number) {
const correct = new Audio("Sounds/correct.mp3");
correct.play();
document.querySelector(".wrapper").style.display="none";
document.querySelector(".well-done").style.display="block";
After this I also noticed that the below needed changing so that it was equal to mathOperator() and not num1 + num2;.
//Places the correct asnwer randomy within the 3 multiple choice answers.
const correctAnswerPosition = Math.floor(Math.random() * 3);
document.querySelectorAll(".options h1")[correctAnswerPosition].textContent = mathoperators();
Thanks for your help Bergi.

Cannot get a JavaScript program to add odd numbers

Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.

I want to write javascript code to get a addition countdown

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!
You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

Calculates and outputs the factorial of variable n (n already initialized).

Here inbelow is the code. Could anybody tell that what's wrong with the code? The purpose is to the factorial result of var n. (suppose it's already declared)
for(var i = 0; i < 5; i++)
{
var n1 = Math.floor(rc4Rand.getRandomNumber() * 7) + 3;
document.write("The factorial of " + n1 + " is ");
outputFactorial(n1);
}
function outputFactorial(n)
{
//I have to add some context here to post this question.
if (n1 == 0) {
return 1;
}
else {
return (n1 * factorial(n1 - 1));
}
}
document.write(n);
Simple mistake: the name of the argument in your outputFactorial() function is n, but you're using n1 throughout the function, and thus entering an infinite recursion loop (if n1 != 0).
The factorial function must be change to outputFactorial
The n1 variables needs to be changed to n in the outputFactorial function
You have to do is Document.write(outputFactorial(n1));
Remove the outside of function Document.write

If Statement? Don't add numbers into total variable if they are negative

Question, how do I make it so when an user-inputted number is negative, it isn't added to the total variable that will be ouput?
Code below!
function lab10logicInLoopsPart1()
{
lCounter = 1;
var total = 0;
userNumber = 0;
while(lCounter < 6) {
lCounter++;
userNumber = prompt("Enter a number.");
total += +userNumber;
document.write("Entered number was: " + userNumber + "\n");
}
document.write("\nTotal: " + total);
}
After prompting the user to enter a number, just check it's not a negative with an if statement:
if(userNumber >=0)
{ //do your stuff here}

Categories

Resources